ASP.NET Core 2.0 Preview 1:如何使用自定义登录路径设置Cookie身份验证

Ric*_*ahl 11 c# authentication cookies asp.net-core

在ASP.NET Core 2.0中,.UseAuthentication()中间件有一个重大更改,不再允许此处提到旧语法工作.

新版本似乎在addAuthentication中处理配置,但我无法在任何地方找到有关如何更改指定自定义登录和注销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;
        });
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激...

Ric*_*ahl 13

更新后,在2.0 RTM位中再次略有改变

事实证明它比预期的要容易得多,但由于官方文档还没有更新,这正是适用于纯Cookie的身份验证:

组态:

ConfigureServices()配置特定的身份验证机制:

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

然后Configure()实际连接中间件:

app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

使用Auth组件

然后使用实际的Auth组件,逻辑已经从HttpContext.Authentication对象转移到仅仅HttpContext在控制器代码之类的应用程序逻辑中:

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(identity));
Run Code Online (Sandbox Code Playgroud)

要么:

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
Run Code Online (Sandbox Code Playgroud)

  • 只需注意:您需要添加此nuget包:CookieAuthenticationDefaults的"Microsoft.AspNetCore.Authentication.Cookies",***默认值等. (3认同)

Tse*_*eng 10

您发布的示例似乎并不是真正的代码(即new CookieAuthenticationOptions()在AddAuthentication调用内部,而不是作为参数AddCookieAuthentication).您不在AddAuthorization通话中添加授权,只需在设置标准中间件,请参阅此公告.

旧:

services.AddAuthentication(sharedOptions => 
       sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
   AutomaticChallenge = true,
   AutomaticAuthenticate = true,
Run Code Online (Sandbox Code Playgroud)

新:

app.AddAuthentication(o => {
   o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
   o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
   o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
Run Code Online (Sandbox Code Playgroud)

而且

services.AddXxxAuthentication(new XxxOptions() { ... });
Run Code Online (Sandbox Code Playgroud)

被替换为

services.AddXxxAuthentication(options => {
});
Run Code Online (Sandbox Code Playgroud)

与所有其他接受配置的方法一致.

另外非常值得一看ASP.NET核心公告GitHub的仓库,那里的ASP.NET核心团队宣布突破的下一个版本的变化,只是选择一个特定的里程碑出现,即2.0.0-preview1,2.0.0-preview2,等等