ASP.NET Core中Cookie验证身份用法详解

2022-04-17 03:04:35
目录
添加配置ASP.NETCore1.xASP.NETCore2.x创建身份认证CookieASP.NETCore1.xASP.NETCore2.xSigningout(登出)ASP.NETCore1.xASP.NETCore2.x服务端变化反馈ASP.NETCore1.xASP.NETCore2.xCookie设置选项ASP.NETCore1.xASP.NETCore2.x持久CookieASP.NETCore1.xASP.NETCore2.x绝对到期时间ASP.NETCore1.xASP.NETCore2.x

ASP.NET Core 1.x提供了通过Cookie 中间件将用户主体序列化为一个加密的Cookie,然后在后续请求中验证Cookie并重新创建主体,并将其分配给HttpContext.User属性。如果您要提供自己的登录界面和用户数据库,可以使用作为独立功能的Cookie中间件。

ASP.NET Core 2.x的一个主要变化是不再存在Cookie中间件。取而代之的是在Startup.cs文件中的Configure方法中的调用UseAuthentication方法会添加设置HttpContext.User属性的 AuthenticationMiddleware 中间件。

添加配置

ASP.NET Core 1.x

按下列步骤操作:

在您的项目中安装Microsoft.AspNetCore.Authentication.CookiesNuGet包。此包包含Cookie中间件。

在Startup.cs文件中的Configure方法中添加下面的行,在app.UseMvc()语句之前:

        app.UseCookieAuthentication(new CookieAuthenticationOptions()        {            AccessDeniedPath = "/Account/Forbidden/",            AuthenticationScheme = "MyCookieAuthenticationScheme",            AutomaticAuthenticate = true,            AutomaticChallenge = true,            LoginPath = "/Account/Unauthorized/"        });

ASP.NET Core 2.x

按下列步骤操作:

如果不使用Microsoft.AspNetCore.All 元包,则在您的项目中安装2.0版的Microsoft.AspNetCore.Authentication.CookiesNuGet包。

在Startup.cs文件中的Configure方法中调用UseAuthentication方法:

        app.UseAuthentication();
在Startup.cs文件中的ConfigureServices方法中调用AddAuthenticationAddCookie方法:
        services.AddAuthentication("MyCookieAuthenticationScheme")                .AddCookie("MyCookieAuthenticationScheme", options => {                    options.AccessDeniedPath = "/Account/Forbidden/";                    options.LoginPath = "/Account/Unauthorized/";                });

上面的代码片段配置了以下部分或全部选项:

AccessDeniedPath - 当用户尝试访问资源但没有通过任何授权策略时,这是请求会重定向的相对路径资源。AuthenticationScheme - 这是一个已知的特定Cookie认证方案的值。当有多个Cookie验证实例,并且您想限制对一个实例的授权时,这就非常有用。AutomaticAuthenticate - 此标识仅适用于ASP.NET Core 1.x。它表示Cookie身份验证应在每个请求上运行,并尝试验证和重建序列化主体。AutomaticChallenge - 此标识仅适用于ASP.NET Core 1.x。这表示当授权失败时,1.x Cookie认证应将浏览器重定向到LoginPathAccessDeniedPathLoginPath - 当用户尝试访问资源但尚未认证时,这是请求重定向的相对路径。

其它选项包括为Cookie认证创建的设置选项,身份验证的Cookie的名称,Cookie的域和Cookie各种安全属性。默认情况下,Cookie身份验证为其创建的任何Cookie使用适当的安全选项,例如:

设置HttpOnly标志以防止客户端javascript中访问Cookie如果请求是通过HTTPS访问,则将Cookie限制为HTTPS

创建身份认证Cookie

要创建一个保存用户信息的cookie,您必须构建一个ClaimsPrincipal 保存您希望序列化到Cookie中的信息。

ASP.NET Core 1.x

    await HttpContext.Authentication.SignInAsync("MyCookieAuthenticationScheme", principal);

ASP.NET Core 2.x

    await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal);

这将创建一个加密的Cookie并将其添加到当前响应中。在调用SignInAsync时,必须在配置中指定的AuthenticationScheme

顺便提一下,使用的加密方式是ASP.NET Core的Data Protection系统。如果您在多台机器上进行托管、负载平衡或使用Web集群,则需要配置Data Protection才能使用相同的密钥和应用程序标识符。

Signing out(登出)

要退出当前用户并删除其Cookie,请在控制器中调用以下方法:

ASP.NET Core 1.x

    await HttpContext.Authentication.SignOutAsync("MyCookieAuthenticationScheme");

ASP.NET Core 2.x

    await HttpContext.SignOutAsync("MyCookieAuthenticationScheme");

服务端变化反馈

能是用户显示同意,在登录时的“记住我”复选框或类似的机制启用。您可以通过在创建身份认证Cookie时调用的SignInAsync方法中使用AuthenticationProperties参数来执行这些操作。例如:

ASP.NET www.easck.comCore 1.x

    await HttpContext.Authentication.SignInAsync(        "MyCookieAuthenticationScheme",        principal,        new AuthenticationProperties        {            IsPersistent = true        });

上述代码片段中使用的AuthenticationProperties类,位于Microsoft.AspNetCore.Http.Authentication命名空间中。

ASP.NET Core 2.x

    await HttpContext.SignInAsync(        "MyCookieAuthenticationScheme",        principal,        new AuthenticationProperties        {            IsPersistent = true        });

上述代码片段中使用的AuthenticationProperties类,位于Microsoft.AspNetCore.Authentication命名空间中。

上面的代码段创建一个身份和相应的Cookie,直到浏览器关闭。以前通过Cookie设置选项配置的任何滑动过期设置仍然有效。如果Cookie在浏览器关闭时过期,浏览器会在重新启动后清除它。如果Cookie在浏览器关闭时过期,浏览器会在重新启动后清除它。

绝对到期时间

ASP.NET Core 1.x

    await HttpContext.Authentication.SignInAsync(        "MyCookieAuthenticationScheme",        principal,        new AuthenticationProperties        {            ExpiresUtc = DateTime.UtcNow.AddMinutes(20)        });

ASP.NET Core 2.x

    await HttpContext.SignInAsync(        "MyCookieAuthenticationScheme",        principal,        new AuthenticationProperties        {            ExpiresUtc = DateTime.UtcNow.AddMinutes(20)        });

上述代码段创建一个持续20分钟的身份和相应的cookie。这将忽略以前通过Cookie设置选项配置的任何滑动过期设置。

ExpiresUtcIsPersistent属性是互斥的。

到此这篇关于ASP.NET Core中Cookie验证身份用法详解的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。