I upgraded from ASP.NET Core 1.1 to 2.0 and am now having 401 Unauthorized responses get changed to 302 Redirect responses. This was previously an issue for me in 1.1 and was mitigated with the following code:
services.AddIdentity<User, IdentityRole>(identityOptions =>
{
identityOptions.Cookies.ApplicationCookie.AutomaticChallenge = false;
})
However, there is no longer a Cookies
property on identityOptions
.
I have tried adding the following as well (and also note that I previously did not need this extension method in my app):
services.AddCookieAuthentication(cookieAuthenticationOptions => {
cookieAuthenticationOptions.LoginPath = ""; // also tried null
cookieAuthenticationOptions.AccessDeniedPath = ""; // also tried null
cookieAuthenticationOptions.LogoutPath = ""; // also tried null
});
That code appears to have no effect to the default redirect paths or behaviors. How can I prevent these redirects in Core 2.0?
As explained in https://github.com/aspnet/Announcements/issues/262, you must now configure the default scheme handlers at the global level, using the services.AddAuthentication()
extension.
To prevent the cookies handlers registered by Identity from handling challenges, replace DefaultChallengeScheme
by the scheme corresponding to a different handler (e.g the JWT bearer handler).
services.AddIdentity<User, IdentityRole>();
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
});
If - for whatever reason - choosing a different handler is not an option for you, then you'll have to use services.ConfigureApplicationCookie()
to register a custom CookieAuthenticationEvents.(On)RedirectToLogin
event to change the way Identity returns a "unauthorized response".
Here's an example returning a 401 response:
services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With