ASP.NET Core 2.0 Preview 1: How to set up Cookie Authentication with custom login path

前端 未结 2 1957
广开言路
广开言路 2020-12-16 18:45

In ASP.NET Core 2.0 the .UseAuthentication() middleware has a breaking change that no longer allows the old syntax mentioned here to work.

The new version appears to

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 19:31

    Updated as this has changed slightly again in the 2.0 RTM bits

    It turns out it's a lot easier than expected, but as the official documentation hasn't been updated yet, here is exactly what works for plain Cookie auth:

    Configuration:

    In ConfigureServices() configure the specific Authentication mechanism:

    services
        .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(o =>
        {
            o.LoginPath = "/api/login";
            o.LogoutPath = "/api/logout";
            // additional config options here
        });
    

    Then in Configure() to actually hook up the middleware:

    app.UseAuthentication();
    

    Using the Auth Components

    Then to use the actual Auth components the logic has shifted from the HttpContext.Authentication object, down to just HttpContext in application logic like controller code:

    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(identity));
    

    or:

    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    

提交回复
热议问题