简体   繁体   中英

Upgrading cookie authentication in a SPA to .NET Core 2.0

I have a SPA I wish to upgrade to .NET Core 2.0 Web API

Out of the box .NET Core has very poor cookie authentication for SPA as all the middleware assumes that you want to redirect to /Account/Login .

In a single page application an authentication redirection is useless (there is no login page) - instead I need a 401 response that tells the client side JS to ask the user to log in.

To work around this in .NET Core 1.1 I had to allow the AutomaticChallenge to fire and then override the event...

services.AddIdentity<AppUser, AppRole>(options =>
{
    var c = options.Cookies.ApplicationCookie;
    c.AuthenticationScheme = "MyScheme";
    c.CookieName = "MyCookieName";
    c.AutomaticAuthenticate = true;

    // This is a total cludge: AutomaticChallenge causes something deep in .NET to auto respond with a 302 redirect to ~/account/login
    c.AutomaticChallenge = true;
    c.LoginPath = PathString.Empty; // LoginPath defaults to ~/account/login
    c.Events = new CookieAuthenticationEvents
    {
         // Override the 302 redirection with the 401 we actually want 
         OnRedirectToLogin = context =>
         {
             context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
             return Task.FromResult(0);
         }
     };
})

This was a cludge, but it worked. In .NET Core 2.0 it has been deprecated.

I've tried moving this to services.ConfigureApplicationCookie , but while the cookie name and other properties are configured the CookieAuthenticationEvents.OnRedirectToLogin is ignored.

I've tried moving this to services.AddAuthentication(...).AddCookie() as suggested in the official docs , but those settings are just ignored. services.Configure<CookieAuthenticationOptions> behaves the same way.

How do I set up a .NET Core 2.0 Web API so that if the request does not have a valid authentication cookie it returns an HTTP 401 status?

In the Authentication 2.0 stack, the configuration of the application cookie is no longer part of identityOptions. Please see Auth 2.0 Changes

services.ConfigureApplicationCookie(o =>
        {
            o.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = (ctx) =>
                {
                    if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                    {
                        ctx.Response.StatusCode = 401;
                    }

                    return Task.CompletedTask;
                },
                OnRedirectToAccessDenied = (ctx) =>
                {
                    if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                    {
                        ctx.Response.StatusCode = 403;
                    }

                    return Task.CompletedTask;
                }
            };
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM