Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the replacement for Cookies.ApplicationCookie.AutomaticChallenge = false in ASP.NET Core 2.0 Identity?

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?

like image 691
Matthew Steven Monkan Avatar asked Jul 23 '17 22:07

Matthew Steven Monkan


1 Answers

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;
    };
});
like image 97
Kévin Chalet Avatar answered Oct 18 '22 21:10

Kévin Chalet