Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

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

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 deal with config in addAuthentication, but I can't find any details anywhere on how to change my old code that specified a custom login and logout url.

        services.AddAuthentication(o =>
        {
            // Where can I specify this?????
            var opt = new CookieAuthenticationOptions()
            {
                LoginPath = "/api/login",
                LogoutPath = "/api/logout",
            };

           o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
           o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        });

Any help would be appreciated...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...