cookie不使用身份验证ASP.NET Core IdentityUse cookie authentication without ASP.NET Core Identity

作者:Rick AndersonBy Rick Anderson

ASP.NET Core Identity 是一个完整的全功能身份验证提供程序,用于创建和维护登录名。ASP.NET Core Identity is a complete, full-featured authentication provider for creating and maintaining logins. 但是, cookie 不能使用基于的身份验证提供程序 ASP.NET Core Identity 。However, a cookie-based authentication provider without ASP.NET Core Identity can be used. 有关详细信息,请参阅 ASP.NET Core 简介 IdentityFor more information, see ASP.NET Core 简介 Identity.

查看或下载示例代码如何下载View or download sample code (how to download)

出于演示目的,在示例应用程序中,假设用户(Maria Rodriguez)的用户帐户已硬编码到应用中。For demonstration purposes in the sample app, the user account for the hypothetical user, Maria Rodriguez, is hardcoded into the app. 使用 电子邮件 地址 maria.rodriguez@contoso.com 和任何密码来登录用户。Use the Email address maria.rodriguez@contoso.com and any password to sign in the user. 用户通过 AuthenticateUser 页面/帐户/登录名. .cs 文件中的方法进行身份验证。The user is authenticated in the AuthenticateUser method in the Pages/Account/Login.cshtml.cs file. 在实际的示例中,用户将对数据库进行身份验证。In a real-world example, the user would be authenticated against a database.

配置Configuration

如果应用程序不使用 AspNetCore 元包,请在项目文件中为 AspNetCore 创建包引用 。 Cookies 包。If the app doesn't use the Microsoft.AspNetCore.App metapackage, create a package reference in the project file for the Microsoft.AspNetCore.Authentication.Cookies package.

Startup.ConfigureServices 方法中,创建具有和方法的身份验证中间件服务 AddAuthentication AddCookieIn the Startup.ConfigureServices method, create the Authentication Middleware services with the AddAuthentication and AddCookie methods:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

AuthenticationScheme 传递以 AddAuthentication 设置应用程序的默认身份验证方案。AuthenticationScheme passed to AddAuthentication sets the default authentication scheme for the app. AuthenticationScheme 如果有多个 cookie 身份验证实例,并且你想要 使用特定方案进行授权,则会很有用。AuthenticationScheme is useful when there are multiple instances of cookie authentication and you want to authorize with a specific scheme. 将设置 AuthenticationScheme Cookie AuthenticationDefaults。 AuthenticationScheme为方案提供值 " Cookie s"。Setting the AuthenticationScheme to CookieAuthenticationDefaults.AuthenticationScheme provides a value of "Cookies" for the scheme. 可以提供任何用于区分方案的字符串值。You can supply any string value that distinguishes the scheme.

应用的身份验证方案不同于应用的 cookie 身份验证方案。The app's authentication scheme is different from the app's cookie authentication scheme. 当 cookie 未提供身份验证方案时 AddCookie ,它将使用 CookieAuthenticationDefaults.AuthenticationScheme ( " Cookie s" ) 。When a cookie authentication scheme isn't provided to AddCookie, it uses CookieAuthenticationDefaults.AuthenticationScheme ("Cookies").

cookie默认情况下,身份验证的 IsEssential 属性设置为 trueThe authentication cookie's IsEssential property is set to true by default. cookie当站点访问者未同意数据收集时,允许使用身份验证。Authentication cookies are allowed when a site visitor hasn't consented to data collection. 有关详细信息,请参阅 ASP.NET Core 中一般数据保护条例 (GDPR) 支持For more information, see ASP.NET Core 中一般数据保护条例 (GDPR) 支持.

在中 Startup.Configure ,调用 UseAuthenticationUseAuthorization 设置 HttpContext.User 属性并为请求运行授权中间件。In Startup.Configure, call UseAuthentication and UseAuthorization to set the HttpContext.User property and run Authorization Middleware for requests. UseAuthentication UseAuthorization 在调用之前调用和方法 UseEndpointsCall the UseAuthentication and UseAuthorization methods before calling UseEndpoints:

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapRazorPages();
});

CookieAuthenticationOptions类用于配置身份验证提供程序选项。The CookieAuthenticationOptions class is used to configure the authentication provider options.

CookieAuthenticationOptions 服务配置中设置,以便在方法中进行身份验证 Startup.ConfigureServicesSet CookieAuthenticationOptions in the service configuration for authentication in the Startup.ConfigureServices method:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        ...
    });

Cookie 策略中间件Cookie Policy Middleware

Cookie 策略中间件启用 cookie 策略功能。Cookie Policy Middleware enables cookie policy capabilities. 将中间件添加到应用处理管道是区分顺序的, — 它仅影响在管道中注册的下游组件。Adding the middleware to the app processing pipeline is order sensitive—it only affects downstream components registered in the pipeline.

app.UseCookiePolicy(cookiePolicyOptions);

使用 CookiePolicyOptions 提供给 Cookie 策略中间件来控制 cookie cookie 在 cookie 追加或删除时处理和挂钩处理处理程序的全局特性。Use CookiePolicyOptions provided to the Cookie Policy Middleware to control global characteristics of cookie processing and hook into cookie processing handlers when cookies are appended or deleted.

默认 MinimumSameSitePolicy 值为 SameSiteMode.Lax 允许 OAuth2 authentication。The default MinimumSameSitePolicy value is SameSiteMode.Lax to permit OAuth2 authentication. 若要严格地强制执行同一站点策略 SameSiteMode.Strict ,请设置 MinimumSameSitePolicyTo strictly enforce a same-site policy of SameSiteMode.Strict, set the MinimumSameSitePolicy. 尽管此设置会中断 OAuth2 和其他跨源身份验证方案,但它会提升 cookie 其他不依赖于跨源请求处理的应用类型的安全级别。Although this setting breaks OAuth2 and other cross-origin authentication schemes, it elevates the level of cookie security for other types of apps that don't rely on cross-origin request processing.

var cookiePolicyOptions = new CookiePolicyOptions
{
    MinimumSameSitePolicy = SameSiteMode.Strict,
};

的 Cookie 策略中间件设置会 MinimumSameSitePolicy 影响中的设置 Cookie.SameSiteCookieAuthenticationOptions 具体取决于下面的矩阵。The Cookie Policy Middleware setting for MinimumSameSitePolicy can affect the setting of Cookie.SameSite in CookieAuthenticationOptions settings according to the matrix below.

MinimumSameSitePolicyMinimumSameSitePolicy Cookie.SameSiteCookie.SameSite 结果 Cookie 。SameSite 设置Resultant Cookie.SameSite setting
SameSiteModeSameSiteMode.None SameSiteModeSameSiteMode.None
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.None
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Lax SameSiteModeSameSiteMode.None
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Strict SameSiteModeSameSiteMode.None
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Strict

创建身份验证 cookieCreate an authentication cookie

若要创建 cookie 保存用户信息,请构造 ClaimsPrincipalTo create a cookie holding user information, construct a ClaimsPrincipal. 将序列化用户信息并将其存储在中 cookie 。The user information is serialized and stored in the cookie.

ClaimsIdentity使用任何所需的 Claim 和调用 SignInAsync 来登录用户:Create a ClaimsIdentity with any required Claims and call SignInAsync to sign in the user:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, user.Email),
    new Claim("FullName", user.FullName),
    new Claim(ClaimTypes.Role, "Administrator"),
};

var claimsIdentity = new ClaimsIdentity(
    claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
    //AllowRefresh = <bool>,
    // Refreshing the authentication session should be allowed.

    //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
    // The time at which the authentication ticket expires. A 
    // value set here overrides the ExpireTimeSpan option of 
    // CookieAuthenticationOptions set with AddCookie.

    //IsPersistent = true,
    // Whether the authentication session is persisted across 
    // multiple requests. When used with cookies, controls
    // whether the cookie's lifetime is absolute (matching the
    // lifetime of the authentication ticket) or session-based.

    //IssuedUtc = <DateTimeOffset>,
    // The time at which the authentication ticket was issued.

    //RedirectUri = <string>
    // The full path or absolute URI to be used as an http 
    // redirect response value.
};

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

若要查看翻译为非英语语言的代码注释,请在 此 GitHub 讨论问题中告诉我们。If you would like to see code comments translated to languages other than English, let us know in this GitHub discussion issue.

SignInAsync 创建一个加密的 cookie ,并将其添加到当前响应中。SignInAsync creates an encrypted cookie and adds it to the current response. 如果 AuthenticationScheme 未指定,则使用默认方案。If AuthenticationScheme isn't specified, the default scheme is used.

RedirectUri 默认情况下,仅在几个特定路径上使用,例如登录路径和注销路径。RedirectUri is only used on a few specific paths by default, for example, the login path and logout paths. 有关详细信息,请参阅 Cookie AuthenticationHandler 源For more information see the CookieAuthenticationHandler source.

ASP.NET Core 的 数据保护 系统用于加密。ASP.NET Core's Data Protection system is used for encryption. 对于托管在多台计算机上的应用程序、跨应用程序或使用 web 场进行负载平衡,请 将数据保护配置 为使用相同的密钥环和应用程序标识符。For an app hosted on multiple machines, load balancing across apps, or using a web farm, configure data protection to use the same key ring and app identifier.

注销Sign out

若要注销当前用户并将其删除 cookie ,请调用 SignOutAsyncTo sign out the current user and delete their cookie, call SignOutAsync:

await HttpContext.SignOutAsync(
    CookieAuthenticationDefaults.AuthenticationScheme);

如果 CookieAuthenticationDefaults.AuthenticationScheme (或 " Cookie s" ) 未用作方案 (例如 "Contoso Cookie " ) ,请提供配置身份验证提供程序时所使用的方案。If CookieAuthenticationDefaults.AuthenticationScheme (or "Cookies") isn't used as the scheme (for example, "ContosoCookie"), supply the scheme used when configuring the authentication provider. 否则,将使用默认方案。Otherwise, the default scheme is used.

当浏览器关闭时,它将自动删除基于会话 cookie 的 (非持久 cookie) ,但 cookie 当关闭单个选项卡时,将不会清除任何。When the browser closes it automatically deletes session based cookies (non-persistent cookies), but no cookies are cleared when an individual tab is closed. 未向服务器通知选项卡或浏览器关闭事件。The server is not notified of tab or browser close events.

对后端更改作出反应React to back-end changes

一旦 cookie 创建, cookie 就是标识的单个源。Once a cookie is created, the cookie is the single source of identity. 如果在后端系统中禁用用户帐户:If a user account is disabled in back-end systems:

  • 应用的 cookie 身份验证系统将继续根据身份验证处理请求 cookie 。The app's cookie authentication system continues to process requests based on the authentication cookie.
  • 只要身份验证有效,用户就会保持登录到应用 cookie 。The user remains signed into the app as long as the authentication cookie is valid.

ValidatePrincipal事件可用于截获和重写 cookie 标识验证。The ValidatePrincipal event can be used to intercept and override validation of the cookie identity. 验证 cookie 每个请求是否会降低吊销用户访问应用的风险。Validating the cookie on every request mitigates the risk of revoked users accessing the app.

验证的一种方法 cookie 是基于跟踪用户数据库更改的时间。One approach to cookie validation is based on keeping track of when the user database changes. 如果自用户颁发以来数据库尚未发生更改 cookie ,则无需重新对用户进行身份验证,前提 cookie 是用户仍有效。If the database hasn't been changed since the user's cookie was issued, there's no need to re-authenticate the user if their cookie is still valid. 在示例应用中,数据库在中实现 IUserRepository 并存储一个 LastChanged 值。In the sample app, the database is implemented in IUserRepository and stores a LastChanged value. 当用户在数据库中更新时,该值将 LastChanged 设置为当前时间。When a user is updated in the database, the LastChanged value is set to the current time.

为了使 cookie 数据库根据值发生更改时失效 LastChanged ,请 cookie 使用 LastChanged 包含数据库中的当前值的声明创建 LastChangedIn order to invalidate a cookie when the database changes based on the LastChanged value, create the cookie with a LastChanged claim containing the current LastChanged value from the database:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, user.Email),
    new Claim("LastChanged", {Database Value})
};

var claimsIdentity = new ClaimsIdentity(
    claims, 
    CookieAuthenticationDefaults.AuthenticationScheme);

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

若要为事件实现替代 ValidatePrincipal ,请在派生自的类中编写具有以下签名的方法 CookieAuthenticationEventsTo implement an override for the ValidatePrincipal event, write a method with the following signature in a class that derives from CookieAuthenticationEvents:

ValidatePrincipal(CookieValidatePrincipalContext)

下面是的示例实现 CookieAuthenticationEventsThe following is an example implementation of CookieAuthenticationEvents:

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
{
    private readonly IUserRepository _userRepository;

    public CustomCookieAuthenticationEvents(IUserRepository userRepository)
    {
        // Get the database from registered DI services.
        _userRepository = userRepository;
    }

    public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
    {
        var userPrincipal = context.Principal;

        // Look for the LastChanged claim.
        var lastChanged = (from c in userPrincipal.Claims
                           where c.Type == "LastChanged"
                           select c.Value).FirstOrDefault();

        if (string.IsNullOrEmpty(lastChanged) ||
            !_userRepository.ValidateLastChanged(lastChanged))
        {
            context.RejectPrincipal();

            await context.HttpContext.SignOutAsync(
                CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }
}

cookie在方法中注册服务期间注册事件实例 Startup.ConfigureServicesRegister the events instance during cookie service registration in the Startup.ConfigureServices method. 提供类的 作用域服务注册 CustomCookieAuthenticationEventsProvide a scoped service registration for your CustomCookieAuthenticationEvents class:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.EventsType = typeof(CustomCookieAuthenticationEvents);
    });

services.AddScoped<CustomCookieAuthenticationEvents>();

请考虑这样一种情况:用户的名称更新为 — 不影响安全的决策。Consider a situation in which the user's name is updated—a decision that doesn't affect security in any way. 如果要以非破坏性的更新用户主体,请调用, context.ReplacePrincipal 并将 context.ShouldRenew 属性设置为 trueIf you want to non-destructively update the user principal, call context.ReplacePrincipal and set the context.ShouldRenew property to true.

警告

此处所述的方法在每个请求时触发。The approach described here is triggered on every request. 验证 cookie 每个请求的所有用户的身份验证可能会导致应用程序的性能下降。Validating authentication cookies for all users on every request can result in a large performance penalty for the app.

持久性 cookiePersistent cookies

你可能希望在 cookie 浏览器会话之间保持。You may want the cookie to persist across browser sessions. 仅当登录或类似机制上出现 "记住我" 复选框时,才应启用此持久性。This persistence should only be enabled with explicit user consent with a "Remember Me" check box on sign in or a similar mechanism.

下面的代码片段将创建一个标识,并 cookie 在浏览器闭包中置对应。The following code snippet creates an identity and corresponding cookie that survives through browser closures. 预先配置的任何可调过期设置都将起作用。Any sliding expiration settings previously configured are honored. 如果 cookie 浏览器关闭时过期,浏览器会在 cookie 重新启动后将其清除。If the cookie expires while the browser is closed, the browser clears the cookie once it's restarted.

设置 IsPersistenttrue in AuthenticationPropertiesSet IsPersistent to true in AuthenticationProperties:

// using Microsoft.AspNetCore.Authentication;

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    new AuthenticationProperties
    {
        IsPersistent = true
    });

绝对 cookie 过期Absolute cookie expiration

绝对过期时间可以设置为 ExpiresUtcAn absolute expiration time can be set with ExpiresUtc. 若要创建持久 cookie , IsPersistent 还必须设置。To create a persistent cookie, IsPersistent must also be set. 否则, cookie 创建时使用基于会话的生存期,并且可能会在它所包含的身份验证票证之前或之后过期。Otherwise, the cookie is created with a session-based lifetime and could expire either before or after the authentication ticket that it holds. 设置后, ExpiresUtc 它将覆盖的 ExpireTimeSpan 选项的值 CookieAuthenticationOptions (如果已设置)。When ExpiresUtc is set, it overrides the value of the ExpireTimeSpan option of CookieAuthenticationOptions, if set.

下面的代码片段将创建一个标识,并将 cookie 持续20分钟。The following code snippet creates an identity and corresponding cookie that lasts for 20 minutes. 这将忽略以前配置的任何可调过期设置。This ignores any sliding expiration settings previously configured.

// using Microsoft.AspNetCore.Authentication;

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    new AuthenticationProperties
    {
        IsPersistent = true,
        ExpiresUtc = DateTime.UtcNow.AddMinutes(20)
    });

ASP.NET Core Identity 是一个完整的全功能身份验证提供程序,用于创建和维护登录名。ASP.NET Core Identity is a complete, full-featured authentication provider for creating and maintaining logins. 但是, cookie 不能使用基于的身份验证提供程序 ASP.NET Core Identity 。However, a cookie-based authentication provider without ASP.NET Core Identity can be used. 有关详细信息,请参阅 ASP.NET Core 简介 IdentityFor more information, see ASP.NET Core 简介 Identity.

查看或下载示例代码如何下载View or download sample code (how to download)

出于演示目的,在示例应用程序中,假设用户(Maria Rodriguez)的用户帐户已硬编码到应用中。For demonstration purposes in the sample app, the user account for the hypothetical user, Maria Rodriguez, is hardcoded into the app. 使用 电子邮件 地址 maria.rodriguez@contoso.com 和任何密码来登录用户。Use the Email address maria.rodriguez@contoso.com and any password to sign in the user. 用户通过 AuthenticateUser 页面/帐户/登录名. .cs 文件中的方法进行身份验证。The user is authenticated in the AuthenticateUser method in the Pages/Account/Login.cshtml.cs file. 在实际的示例中,用户将对数据库进行身份验证。In a real-world example, the user would be authenticated against a database.

配置Configuration

如果应用程序不使用 AspNetCore 元包,请在项目文件中为 AspNetCore 创建包引用 。 Cookies 包。If the app doesn't use the Microsoft.AspNetCore.App metapackage, create a package reference in the project file for the Microsoft.AspNetCore.Authentication.Cookies package.

Startup.ConfigureServices 方法中,创建具有和方法的身份验证中间件服务 AddAuthentication AddCookieIn the Startup.ConfigureServices method, create the Authentication Middleware service with the AddAuthentication and AddCookie methods:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

AuthenticationScheme 传递以 AddAuthentication 设置应用程序的默认身份验证方案。AuthenticationScheme passed to AddAuthentication sets the default authentication scheme for the app. AuthenticationScheme 如果有多个 cookie 身份验证实例,并且你想要 使用特定方案进行授权,则会很有用。AuthenticationScheme is useful when there are multiple instances of cookie authentication and you want to authorize with a specific scheme. 将设置 AuthenticationScheme Cookie AuthenticationDefaults。 AuthenticationScheme为方案提供值 " Cookie s"。Setting the AuthenticationScheme to CookieAuthenticationDefaults.AuthenticationScheme provides a value of "Cookies" for the scheme. 可以提供任何用于区分方案的字符串值。You can supply any string value that distinguishes the scheme.

应用的身份验证方案不同于应用的 cookie 身份验证方案。The app's authentication scheme is different from the app's cookie authentication scheme. 当 cookie 未提供身份验证方案时 AddCookie ,它将使用 CookieAuthenticationDefaults.AuthenticationScheme ( " Cookie s" ) 。When a cookie authentication scheme isn't provided to AddCookie, it uses CookieAuthenticationDefaults.AuthenticationScheme ("Cookies").

cookie默认情况下,身份验证的 IsEssential 属性设置为 trueThe authentication cookie's IsEssential property is set to true by default. cookie当站点访问者未同意数据收集时,允许使用身份验证。Authentication cookies are allowed when a site visitor hasn't consented to data collection. 有关详细信息,请参阅 ASP.NET Core 中一般数据保护条例 (GDPR) 支持For more information, see ASP.NET Core 中一般数据保护条例 (GDPR) 支持.

Startup.Configure 方法中,调用 UseAuthentication 方法以调用设置属性的身份验证中间件 HttpContext.UserIn the Startup.Configure method, call the UseAuthentication method to invoke the Authentication Middleware that sets the HttpContext.User property. UseAuthentication在调用或之前调用 UseMvcWithDefaultRoute 方法 UseMvcCall the UseAuthentication method before calling UseMvcWithDefaultRoute or UseMvc:

app.UseAuthentication();

CookieAuthenticationOptions类用于配置身份验证提供程序选项。The CookieAuthenticationOptions class is used to configure the authentication provider options.

CookieAuthenticationOptions 服务配置中设置,以便在方法中进行身份验证 Startup.ConfigureServicesSet CookieAuthenticationOptions in the service configuration for authentication in the Startup.ConfigureServices method:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        ...
    });

Cookie 策略中间件Cookie Policy Middleware

Cookie 策略中间件启用 cookie 策略功能。Cookie Policy Middleware enables cookie policy capabilities. 将中间件添加到应用处理管道是区分顺序的, — 它仅影响在管道中注册的下游组件。Adding the middleware to the app processing pipeline is order sensitive—it only affects downstream components registered in the pipeline.

app.UseCookiePolicy(cookiePolicyOptions);

使用 CookiePolicyOptions 提供给 Cookie 策略中间件来控制 cookie cookie 在 cookie 追加或删除时处理和挂钩处理处理程序的全局特性。Use CookiePolicyOptions provided to the Cookie Policy Middleware to control global characteristics of cookie processing and hook into cookie processing handlers when cookies are appended or deleted.

默认 MinimumSameSitePolicy 值为 SameSiteMode.Lax 允许 OAuth2 authentication。The default MinimumSameSitePolicy value is SameSiteMode.Lax to permit OAuth2 authentication. 若要严格地强制执行同一站点策略 SameSiteMode.Strict ,请设置 MinimumSameSitePolicyTo strictly enforce a same-site policy of SameSiteMode.Strict, set the MinimumSameSitePolicy. 尽管此设置会中断 OAuth2 和其他跨源身份验证方案,但它会提升 cookie 其他不依赖于跨源请求处理的应用类型的安全级别。Although this setting breaks OAuth2 and other cross-origin authentication schemes, it elevates the level of cookie security for other types of apps that don't rely on cross-origin request processing.

var cookiePolicyOptions = new CookiePolicyOptions
{
    MinimumSameSitePolicy = SameSiteMode.Strict,
};

的 Cookie 策略中间件设置会 MinimumSameSitePolicy 影响中的设置 Cookie.SameSiteCookieAuthenticationOptions 具体取决于下面的矩阵。The Cookie Policy Middleware setting for MinimumSameSitePolicy can affect the setting of Cookie.SameSite in CookieAuthenticationOptions settings according to the matrix below.

MinimumSameSitePolicyMinimumSameSitePolicy Cookie.SameSiteCookie.SameSite 结果 Cookie 。SameSite 设置Resultant Cookie.SameSite setting
SameSiteModeSameSiteMode.None SameSiteModeSameSiteMode.None
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.None
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Lax SameSiteModeSameSiteMode.None
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Strict SameSiteModeSameSiteMode.None
SameSiteModeSameSiteMode.Lax
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Strict
SameSiteModeSameSiteMode.Strict

创建身份验证 cookieCreate an authentication cookie

若要创建 cookie 保存用户信息,请构造 ClaimsPrincipalTo create a cookie holding user information, construct a ClaimsPrincipal. 将序列化用户信息并将其存储在中 cookie 。The user information is serialized and stored in the cookie.

ClaimsIdentity使用任何所需的 Claim 和调用 SignInAsync 来登录用户:Create a ClaimsIdentity with any required Claims and call SignInAsync to sign in the user:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, user.Email),
    new Claim("FullName", user.FullName),
    new Claim(ClaimTypes.Role, "Administrator"),
};

var claimsIdentity = new ClaimsIdentity(
    claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
    //AllowRefresh = <bool>,
    // Refreshing the authentication session should be allowed.

    //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
    // The time at which the authentication ticket expires. A 
    // value set here overrides the ExpireTimeSpan option of 
    // CookieAuthenticationOptions set with AddCookie.

    //IsPersistent = true,
    // Whether the authentication session is persisted across 
    // multiple requests. When used with cookies, controls
    // whether the cookie's lifetime is absolute (matching the
    // lifetime of the authentication ticket) or session-based.

    //IssuedUtc = <DateTimeOffset>,
    // The time at which the authentication ticket was issued.

    //RedirectUri = <string>
    // The full path or absolute URI to be used as an http 
    // redirect response value.
};

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

SignInAsync 创建一个加密的 cookie ,并将其添加到当前响应中。SignInAsync creates an encrypted cookie and adds it to the current response. 如果 AuthenticationScheme 未指定,则使用默认方案。If AuthenticationScheme isn't specified, the default scheme is used.

ASP.NET Core 的 数据保护 系统用于加密。ASP.NET Core's Data Protection system is used for encryption. 对于托管在多台计算机上的应用程序、跨应用程序或使用 web 场进行负载平衡,请 将数据保护配置 为使用相同的密钥环和应用程序标识符。For an app hosted on multiple machines, load balancing across apps, or using a web farm, configure data protection to use the same key ring and app identifier.

注销Sign out

若要注销当前用户并将其删除 cookie ,请调用 SignOutAsyncTo sign out the current user and delete their cookie, call SignOutAsync:

await HttpContext.SignOutAsync(
    CookieAuthenticationDefaults.AuthenticationScheme);

如果 CookieAuthenticationDefaults.AuthenticationScheme (或 " Cookie s" ) 未用作方案 (例如 "Contoso Cookie " ) ,请提供配置身份验证提供程序时所使用的方案。If CookieAuthenticationDefaults.AuthenticationScheme (or "Cookies") isn't used as the scheme (for example, "ContosoCookie"), supply the scheme used when configuring the authentication provider. 否则,将使用默认方案。Otherwise, the default scheme is used.

对后端更改作出反应React to back-end changes

一旦 cookie 创建, cookie 就是标识的单个源。Once a cookie is created, the cookie is the single source of identity. 如果在后端系统中禁用用户帐户:If a user account is disabled in back-end systems:

  • 应用的 cookie 身份验证系统将继续根据身份验证处理请求 cookie 。The app's cookie authentication system continues to process requests based on the authentication cookie.
  • 只要身份验证有效,用户就会保持登录到应用 cookie 。The user remains signed into the app as long as the authentication cookie is valid.

ValidatePrincipal事件可用于截获和重写 cookie 标识验证。The ValidatePrincipal event can be used to intercept and override validation of the cookie identity. 验证 cookie 每个请求是否会降低吊销用户访问应用的风险。Validating the cookie on every request mitigates the risk of revoked users accessing the app.

验证的一种方法 cookie 是基于跟踪用户数据库更改的时间。One approach to cookie validation is based on keeping track of when the user database changes. 如果自用户颁发以来数据库尚未发生更改 cookie ,则无需重新对用户进行身份验证,前提 cookie 是用户仍有效。If the database hasn't been changed since the user's cookie was issued, there's no need to re-authenticate the user if their cookie is still valid. 在示例应用中,数据库在中实现 IUserRepository 并存储一个 LastChanged 值。In the sample app, the database is implemented in IUserRepository and stores a LastChanged value. 当用户在数据库中更新时,该值将 LastChanged 设置为当前时间。When a user is updated in the database, the LastChanged value is set to the current time.

为了使 cookie 数据库根据值发生更改时失效 LastChanged ,请 cookie 使用 LastChanged 包含数据库中的当前值的声明创建 LastChangedIn order to invalidate a cookie when the database changes based on the LastChanged value, create the cookie with a LastChanged claim containing the current LastChanged value from the database:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, user.Email),
    new Claim("LastChanged", {Database Value})
};

var claimsIdentity = new ClaimsIdentity(
    claims, 
    CookieAuthenticationDefaults.AuthenticationScheme);

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

若要为事件实现替代 ValidatePrincipal ,请在派生自的类中编写具有以下签名的方法 CookieAuthenticationEventsTo implement an override for the ValidatePrincipal event, write a method with the following signature in a class that derives from CookieAuthenticationEvents:

ValidatePrincipal(CookieValidatePrincipalContext)

下面是的示例实现 CookieAuthenticationEventsThe following is an example implementation of CookieAuthenticationEvents:

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
{
    private readonly IUserRepository _userRepository;

    public CustomCookieAuthenticationEvents(IUserRepository userRepository)
    {
        // Get the database from registered DI services.
        _userRepository = userRepository;
    }

    public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
    {
        var userPrincipal = context.Principal;

        // Look for the LastChanged claim.
        var lastChanged = (from c in userPrincipal.Claims
                           where c.Type == "LastChanged"
                           select c.Value).FirstOrDefault();

        if (string.IsNullOrEmpty(lastChanged) ||
            !_userRepository.ValidateLastChanged(lastChanged))
        {
            context.RejectPrincipal();

            await context.HttpContext.SignOutAsync(
                CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }
}

cookie在方法中注册服务期间注册事件实例 Startup.ConfigureServicesRegister the events instance during cookie service registration in the Startup.ConfigureServices method. 提供类的 作用域服务注册 CustomCookieAuthenticationEventsProvide a scoped service registration for your CustomCookieAuthenticationEvents class:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.EventsType = typeof(CustomCookieAuthenticationEvents);
    });

services.AddScoped<CustomCookieAuthenticationEvents>();

请考虑这样一种情况:用户的名称更新为 — 不影响安全的决策。Consider a situation in which the user's name is updated—a decision that doesn't affect security in any way. 如果要以非破坏性的更新用户主体,请调用, context.ReplacePrincipal 并将 context.ShouldRenew 属性设置为 trueIf you want to non-destructively update the user principal, call context.ReplacePrincipal and set the context.ShouldRenew property to true.

警告

此处所述的方法在每个请求时触发。The approach described here is triggered on every request. 验证 cookie 每个请求的所有用户的身份验证可能会导致应用程序的性能下降。Validating authentication cookies for all users on every request can result in a large performance penalty for the app.

持久性 cookiePersistent cookies

你可能希望在 cookie 浏览器会话之间保持。You may want the cookie to persist across browser sessions. 仅当登录或类似机制上出现 "记住我" 复选框时,才应启用此持久性。This persistence should only be enabled with explicit user consent with a "Remember Me" check box on sign in or a similar mechanism.

下面的代码片段将创建一个标识,并 cookie 在浏览器闭包中置对应。The following code snippet creates an identity and corresponding cookie that survives through browser closures. 预先配置的任何可调过期设置都将起作用。Any sliding expiration settings previously configured are honored. 如果 cookie 浏览器关闭时过期,浏览器会在 cookie 重新启动后将其清除。If the cookie expires while the browser is closed, the browser clears the cookie once it's restarted.

设置 IsPersistenttrue in AuthenticationPropertiesSet IsPersistent to true in AuthenticationProperties:

// using Microsoft.AspNetCore.Authentication;

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    new AuthenticationProperties
    {
        IsPersistent = true
    });

绝对 cookie 过期Absolute cookie expiration

绝对过期时间可以设置为 ExpiresUtcAn absolute expiration time can be set with ExpiresUtc. 若要创建持久 cookie , IsPersistent 还必须设置。To create a persistent cookie, IsPersistent must also be set. 否则, cookie 创建时使用基于会话的生存期,并且可能会在它所包含的身份验证票证之前或之后过期。Otherwise, the cookie is created with a session-based lifetime and could expire either before or after the authentication ticket that it holds. 设置后, ExpiresUtc 它将覆盖的 ExpireTimeSpan 选项的值 CookieAuthenticationOptions (如果已设置)。When ExpiresUtc is set, it overrides the value of the ExpireTimeSpan option of CookieAuthenticationOptions, if set.

下面的代码片段将创建一个标识,并将 cookie 持续20分钟。The following code snippet creates an identity and corresponding cookie that lasts for 20 minutes. 这将忽略以前配置的任何可调过期设置。This ignores any sliding expiration settings previously configured.

// using Microsoft.AspNetCore.Authentication;

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    new AuthenticationProperties
    {
        IsPersistent = true,
        ExpiresUtc = DateTime.UtcNow.AddMinutes(20)
    });

其他资源Additional resources