I have two Projects, one is MVC (using Angular) and other is WebAPI. Windows Authentication is working fine in MVC (thanks to this article)
However, when I am making AJAX calls from MVC site through Angular to WebAPI then I get following error:
HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers.
Most likely causes:
- No authentication protocol (including anonymous)is selected in IIS.
- Only integrated authentication is enabled, and a client browser was used that does not support integrated authentication.
- Integrated authentication is enabled and the request was sent through a proxy that changed the authentication headers before they reach the Web server.
- The Web server is not configured for anonymous access and a required authorization header was not received.
- The "configuration/system.webServer/authorization" configuration section may be explicitly denying the user access.
I read this post but it is talking about HttpClient (while I am using JQuery or Angular) to make calls.
PLEASE NOTE: If I hit the WebAPI URL through Browser then Authentication works fine. So it must be something to do with AJAX request.
This is my code in Global.asax
protected void Application_BeginRequest()
{
if (ValidateRequest())
{
//var origin = Request.Headers["Origin"];
Response.Headers.Remove("Access-Control-Allow-Origin");
Response.AddHeader("Access-Control-Allow-Origin", matchedOrigin);
Response.Headers.Remove("Access-Control-Allow-Headers");
Response.AddHeader("Access-Control-Allow-Headers", CustomConfig.HEADERS);
Response.Headers.Remove("Access-Control-Allow-Methods");
Response.AddHeader("Access-Control-Allow-Methods", CustomConfig.METHODS);
}
// This is to avoid "Method 405 Not allowed" error
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
Response.End(); //Send the Empty Response for Options (Preflight Request)
}
}
I have done enough research but couldn't find a solution. So couple of things.
- How can I resolve my above issue
- Secondly what's the best approach for using Windows Authentication based on my scenario (And Project setup).