Wen using the OWIN cookie authentication middleware inside ASP.NET Web API, I noticed that I didn’t got an unauthorized (401) HTTP code when I was not authenticated. Instead the response was a 200 status code with a JSON response body:
{"Message":"Authorization has been denied for this request."}
This is not what I want. To change this you have to reconfigure the CookieAuthenticationProvider on the cookie authentication middleware:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.UseCookieAuthentication(new CookieAuthenticationOptions | |
{ | |
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, | |
LoginPath = new PathString("/Account/Login"), | |
Provider = new CookieAuthenticationProvider | |
{ | |
OnApplyRedirect = ctx => | |
{ | |
if (!IsAjaxRequest(ctx.Request)) | |
{ | |
ctx.Response.Redirect(ctx.RedirectUri); | |
} | |
} | |
} | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private bool IsAjaxRequest(IOwinRequest request) | |
{ | |
IReadableStringCollection query = request.Query; | |
if ((query != null) && (query["X-Requested-With"] == "XMLHttpRequest")) | |
{ | |
return true; | |
} | |
IHeaderDictionary headers = request.Headers; | |
return ((headers != null) && (headers["X-Requested-With"] == "XMLHttpRequest")); | |
} |