We have an asp.net core web app that uses OpenIdDict for authentication. I've noticed that my unauthenticated Ajax calls return a 200 and our login form in the body of the response. From what I've read this is expected behavior since OpenIdDict handles the request, then ASP.NET core handles it and returns the 200. ASP.NET core is handling it because UseIdentity()
is being called in Startup.cs. All of the examples I've seen for OpenIdDict call UseIdentity()
. I have 2 questions.
- If I don't want ASP.NET core to handle my request can I just remove
UseIdentity()
? I tried it and now I get a 401 instead of a 200. Is there any harm in doing this or does OpenIdDict requireUseIdentity()
? - If I don't want to lose the ability for redirects to login for UI Views is the best/simplest/safest method of accomplishing this to override OnRedirectToLogin? Code example below:
options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api") &&
ctx.Response.StatusCode == (int) HttpStatusCode.OK)
{
ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
}
return Task.FromResult(0);
}
};
Code sample source: https://devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/
Further discussion of this issue here: https://github.com/aspnet/Security/issues/804