Search code examples
angularjsasp.net-web-api2asp.net-mvc-5asp.net-authentication

How to prevent 302 redirect using windows authentication


I am building a MVC5 web application with Web API2 for back end server calls and Angularjs for client side code. The application is using windows authentication. For some methods in the Web API controller I have set Authorize attribute on specific user role. The problem is when the authentication failed, it pops up the Windows Security dialog for user to login. Is there a way to prevent this dialog to appear and either redirect to a specific URL or return back a failure status code and error message?

I searched online and found solutions for OWIN authentication but not windows authentication.


Solution

  • Create a Message Handler in Asp.Net Web API where you can remove WWW-Authenticate header, this way the browser will not give a popup.You can do many customization at this level.

    To create you own Message Handler you need to extend the DelegatingHandler like below

     public class MyHandler : DelegatingHandler
     {
           protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
           {
    
                   //Your code goes here
                   var response = await base.SendAsync(request,cancellationToken);
                   if(response.StatusCode == HttpStatusCode.Unauthorized)
                   {
                      // remove WWW-Authenticate from the header and add Location header to redirect to a page
                       OR
                     // Create a new response and then return that response
                   }
                   return response;
    
           }
    
     }