使用 cookie 而无需 ASP.NET Core 标识的身份验证Use cookie authentication without ASP.NET Core Identity

通过Rick AndersonLuke LathamBy Rick Anderson and Luke Latham

如你所见在早期的身份验证主题中, ASP.NET Core 标识完成、 功能完备的身份验证提供程序是用于创建和维护登录名。As you've seen in the earlier authentication topics, ASP.NET Core Identity is a complete, full-featured authentication provider for creating and maintaining logins. 但是,你可能想要使用基于 cookie 的身份验证有时使用您自己的自定义身份验证逻辑。However, you may want to use your own custom authentication logic with cookie-based authentication at times. 你可以使用基于 cookie 的身份验证作为独立身份验证提供程序,没有 ASP.NET Core 标识。You can use cookie-based authentication as a standalone authentication provider without 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 username "maria.rodriguez@contoso.com" and any password to sign in the user. 用户进行身份验证中AuthenticateUser中的方法Pages/Account/Login.cshtml.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.

有关从 ASP.NET Core 迁移基于 cookie 的身份验证信息 1.x 到 2.0,请参阅迁移身份验证和标识到 ASP.NET Core 2.0 主题 (基于 Cookie 的身份验证)For information on migrating cookie-based authentication from ASP.NET Core 1.x to 2.0, see Migrate Authentication and Identity to ASP.NET Core 2.0 topic (Cookie-based Authentication).

若要使用 ASP.NET Core 标识,请参阅标识简介主题。To use ASP.NET Core Identity, see the Introduction to Identity topic.

配置Configuration

如果应用不使用Microsoft.AspNetCore.App 元包,在项目文件中创建的包引用Microsoft.AspNetCore.Authentication.Cookies包 (版本 2.1.0 或更高版本)。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 (version 2.1.0 or later).

在中ConfigureServices方法中,创建具有的身份验证中间件服务AddAuthenticationAddCookie方法:In the 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. 设置AuthenticationSchemeCookieAuthenticationDefaults.AuthenticationScheme方案提供的值为"Cookie"。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")。When a cookie authentication scheme isn't provided to AddCookie, it uses CookieAuthenticationDefaults.AuthenticationScheme ("Cookies").

身份验证 cookieIsEssential属性设置为true默认情况下。The 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) 支持.

Configure 方法中,使用 UseAuthentication 方法调用用于设置 HttpContext.User 属性的身份验证中间件。In the Configure method, use the UseAuthentication method to invoke the Authentication Middleware that sets the HttpContext.User property. 在调用 UseMvcWithDefaultRouteUseMvc 之前调用 UseAuthentication 方法:Call the UseAuthentication method before calling UseMvcWithDefaultRoute or UseMvc:

app.UseAuthentication();

AddCookie OptionsAddCookie Options

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

选项Option 描述Description
AccessDeniedPathAccessDeniedPath 提供的路径以提供 302 已找到 (URL 重定向) 时触发的HttpContext.ForbidAsyncProvides the path to supply with a 302 Found (URL redirect) when triggered by HttpContext.ForbidAsync. 默认值为 /Account/AccessDeniedThe default value is /Account/AccessDenied.
ClaimsIssuerClaimsIssuer 要用于的颁发者颁发者上创建由 cookie 身份验证服务的任何声明的属性。The issuer to use for the Issuer property on any claims created by the cookie authentication service.
Cookie.DomainCookie.Domain Cookie 提供服务位置的域名。The domain name where the cookie is served. 默认情况下,这是请求的主机名。By default, this is the host name of the request. 在浏览器仅将 cookie 在请求中发送到匹配的主机名。The browser only sends the cookie in requests to a matching host name. 您可能希望调整此项是在你的域中有 cookie 提供给任何主机。You may wish to adjust this to have cookies available to any host in your domain. 例如,将 cookie 域设置为.contoso.com使其可供contoso.comwww.contoso.com,和staging.www.contoso.comFor example, setting the cookie domain to .contoso.com makes it available to contoso.com, www.contoso.com, and staging.www.contoso.com.
Cookie.HttpOnlyCookie.HttpOnly 指示是否 cookie 应只允许到服务器可访问的标志。A flag indicating if the cookie should be accessible only to servers. 此值更改为false允许客户端脚本访问 cookie,并可能会打开 cookie 被盗应用应您的应用程序具有跨站点脚本 (XSS)漏洞。Changing this value to false permits client-side scripts to access the cookie and may open your app to cookie theft should your app have a Cross-site scripting (XSS) vulnerability. 默认值为 trueThe default value is true.
Cookie.NameCookie.Name 设置的 cookie 的名称。Sets the name of the cookie.
Cookie.PathCookie.Path 用于隔离同一主机名上运行的应用。Used to isolate apps running on the same host name. 如果必须在运行的应用/app1并且想要将 cookie 限制为该应用,设置CookiePath属性设置为/app1If you have an app running at /app1 and want to restrict cookies to that app, set the CookiePath property to /app1. 通过此操作,cookie 是仅可在请求上/app1和其下的任何应用。By doing so, the cookie is only available on requests to /app1 and any app underneath it.
Cookie.SameSiteCookie.SameSite 指示浏览器是否应允许要附加到同一站点的请求的 cookie (SameSiteMode.Strict) 或使用安全的 HTTP 方法和同一站点的请求的跨站点请求 (SameSiteMode.Lax)。Indicates whether the browser should allow the cookie to be attached to same-site requests only (SameSiteMode.Strict) or cross-site requests using safe HTTP methods and same-site requests (SameSiteMode.Lax). 如果设置为SameSiteMode.None,未设置的 cookie 标头值。When set to SameSiteMode.None, the cookie header value isn't set. 请注意, Cookie 策略中间件可能会覆盖你提供的值。Note that Cookie Policy Middleware might overwrite the value that you provide. 若要支持 OAuth 身份验证,默认值是SameSiteMode.LaxTo support OAuth authentication, the default value is SameSiteMode.Lax. 有关详细信息,请参阅OAuth 身份验证由于 SameSite cookie 策略中断For more information, see OAuth authentication broken due to SameSite cookie policy.
Cookie.SecurePolicyCookie.SecurePolicy 一个标志,指示是否创建的 cookie 应限制为 HTTPS (CookieSecurePolicy.Always),HTTP 或 HTTPS (CookieSecurePolicy.None),或与请求相同的协议 (CookieSecurePolicy.SameAsRequest)。A flag indicating if the cookie created should be limited to HTTPS (CookieSecurePolicy.Always), HTTP or HTTPS (CookieSecurePolicy.None), or the same protocol as the request (CookieSecurePolicy.SameAsRequest). 默认值为 CookieSecurePolicy.SameAsRequestThe default value is CookieSecurePolicy.SameAsRequest.
DataProtectionProviderDataProtectionProvider DataProtectionProvider用于创建默认TicketDataFormatSets the DataProtectionProvider that's used to create the default TicketDataFormat. 如果TicketDataFormat属性设置,DataProtectionProvider选项不会继续使用。If the TicketDataFormat property is set, the DataProtectionProvider option isn't used. 如果未提供,则使用应用程序的默认数据保护提供程序。If not provided, the app's default data protection provider is used.
事件Events 该处理程序处理的特定点上提供的应用程序控制的提供程序上调用方法。The handler calls methods on the provider that give the app control at certain processing points. 如果Events不提供的默认实例提供时才调用这些方法不执行任何操作。If Events aren't provided, a default instance is supplied that does nothing when the methods are called.
EventsTypeEventsType 用作服务类型,以获取Events实例而不是属性。Used as the service type to get the Events instance instead of the property.
ExpireTimeSpanExpireTimeSpan TimeSpan后将存储在 cookie 的身份验证票证到期。The TimeSpan after which the authentication ticket stored inside the cookie expires. ExpireTimeSpan 添加到当前时间来创建票证的到期时间。ExpireTimeSpan is added to the current time to create the expiration time for the ticket. ExpiredTimeSpan值始终会进入加密 AuthTicket 验证服务器。The ExpiredTimeSpan value always goes into the encrypted AuthTicket verified by the server. 此外可能进入Set-cookie标头,但仅当IsPersistent设置。It may also go into the Set-Cookie header, but only if IsPersistent is set. 若要设置IsPersistenttrue,配置AuthenticationProperties传递给SignInAsyncTo set IsPersistent to true, configure the AuthenticationProperties passed to SignInAsync. 默认值ExpireTimeSpan为 14 天。The default value of ExpireTimeSpan is 14 days.
LoginPathLoginPath 提供的路径以提供 302 已找到 (URL 重定向) 时触发的HttpContext.ChallengeAsyncProvides the path to supply with a 302 Found (URL redirect) when triggered by HttpContext.ChallengeAsync. 生成 401 的当前 URL 添加到LoginPath作为查询字符串参数的名为ReturnUrlParameterThe current URL that generated the 401 is added to the LoginPath as a query string parameter named by the ReturnUrlParameter. 一次请求LoginPath授予新登录标识,ReturnUrlParameter值用于将浏览器重定向回导致原始未授权的状态代码的 URL。Once a request to the LoginPath grants a new sign-in identity, the ReturnUrlParameter value is used to redirect the browser back to the URL that caused the original unauthorized status code. 默认值为 /Account/LoginThe default value is /Account/Login.
LogoutPathLogoutPath 如果LogoutPath提供给处理程序,则将重定向到该路径的请求值的基础ReturnUrlParameterIf the LogoutPath is provided to the handler, then a request to that path redirects based on the value of the ReturnUrlParameter. 默认值为 /Account/LogoutThe default value is /Account/Logout.
ReturnUrlParameterReturnUrlParameter 确定由 302 已找到 (URL 重定向) 响应的处理程序追加查询字符串参数的名称。Determines the name of the query string parameter that's appended by the handler for a 302 Found (URL redirect) response. ReturnUrlParameter 请求到达时,将使用LoginPathLogoutPath来执行登录或注销操作后返回到原始 URL 的浏览器。ReturnUrlParameter is used when a request arrives on the LoginPath or LogoutPath to return the browser to the original URL after the login or logout action is performed. 默认值为 ReturnUrlThe default value is ReturnUrl.
SessionStoreSessionStore 一个可选容器,用于标识存储在请求之间。An optional container used to store identity across requests. 使用时,只将会话标识符发送到客户端。When used, only a session identifier is sent to the client. SessionStore 可以用于缓解大型标识的潜在问题。SessionStore can be used to mitigate potential problems with large identities.
SlidingExpirationSlidingExpiration 指示是否应动态颁发包含更新的到期时间的新 cookie 的标志。A flag indicating if a new cookie with an updated expiration time should be issued dynamically. 这可以在任何请求,其中当前 cookie 过期时间已超过 50%过期。This can happen on any request where the current cookie expiration period is more than 50% expired. 向前移动新的到期日期为当前日期加上ExpireTimespanThe new expiration date is moved forward to be the current date plus the ExpireTimespan. 绝对 cookie 到期时间可以通过使用设置AuthenticationProperties类调用时SignInAsyncAn absolute cookie expiration time can be set by using the AuthenticationProperties class when calling SignInAsync. 绝对过期时间可以通过限制身份验证 cookie 是有效的时间量来提高您的应用程序的安全性。An absolute expiration time can improve the security of your app by limiting the amount of time that the authentication cookie is valid. 默认值为 trueThe default value is true.
TicketDataFormatTicketDataFormat TicketDataFormat用于保护和取消保护标识和存储在 cookie 值中的其他属性。The TicketDataFormat is used to protect and unprotect the identity and other properties that are stored in the cookie value. 如果未提供,TicketDataFormat使用创建DataProtectionProviderIf not provided, a TicketDataFormat is created using the DataProtectionProvider.
验证Validate 检查的选项是有效的方法。Method that checks that the options are valid.

设置CookieAuthenticationOptions中的身份验证的服务配置中ConfigureServices方法:Set CookieAuthenticationOptions in the service configuration for authentication in the ConfigureServices method:

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

ASP.NET Core 1.x 使用 cookie中间件,序列化为一个用户主体的加密 cookie。ASP.NET Core 1.x uses cookie middleware that serializes a user principal into an encrypted cookie. 在后续请求中,对 cookie 进行验证,并重新创建和分配给主体HttpContext.User属性。On subsequent requests, the cookie is validated, and the principal is recreated and assigned to the HttpContext.User property.

安装Microsoft.AspNetCore.Authentication.Cookies在项目中的 NuGet 包。Install the Microsoft.AspNetCore.Authentication.Cookies NuGet package in your project. 此包包含 cookie 中间件。This package contains the cookie middleware.

使用UseCookieAuthentication中的方法Configure中的方法您Startup.cs文件,然后UseMvcUseMvcWithDefaultRoute:Use the UseCookieAuthentication method in the Configure method in your Startup.cs file before UseMvc or UseMvcWithDefaultRoute:

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

CookieAuthenticationOptions 选项CookieAuthenticationOptions Options

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

选项Option 描述Description
AuthenticationSchemeAuthenticationScheme 设置身份验证方案。Sets the authentication scheme. AuthenticationScheme 时,可以有多个实例的身份验证,并且你想要与特定方案授权AuthenticationScheme is useful when there are multiple instances of authentication and you want to authorize with a specific scheme. 设置AuthenticationSchemeCookieAuthenticationDefaults.AuthenticationScheme方案提供的值为"Cookie"。Setting the AuthenticationScheme to CookieAuthenticationDefaults.AuthenticationScheme provides a value of "Cookies" for the scheme. 你可以提供任何字符串值,用于区分方案。You can supply any string value that distinguishes the scheme.
AutomaticAuthenticateAutomaticAuthenticate 设置一个值,以指示 cookie 身份验证应在每个请求上运行并尝试验证并重新构造它创建的任何序列化的主体。Sets a value to indicate that the cookie authentication should run on every request and attempt to validate and reconstruct any serialized principal it created.
AutomaticChallengeAutomaticChallenge 如果为 true,则身份验证中间件处理自动挑战。If true, the authentication middleware handles automatic challenges. 如果为 false,身份验证中间件仅更改时进行显式指定响应AuthenticationSchemeIf false, the authentication middleware only alters responses when explicitly indicated by the AuthenticationScheme.
ClaimsIssuerClaimsIssuer 要用于的颁发者颁发者上创建的 cookie 身份验证中间件的任何声明的属性。The issuer to use for the Issuer property on any claims created by the cookie authentication middleware.
CookieDomainCookieDomain Cookie 提供服务位置的域名。The domain name where the cookie is served. 默认情况下,这是请求的主机名。By default, this is the host name of the request. 在浏览器只起到匹配的主机名的 cookie。The browser only serves the cookie to a matching host name. 您可能希望调整此项是在你的域中有 cookie 提供给任何主机。You may wish to adjust this to have cookies available to any host in your domain. 例如,将 cookie 域设置为.contoso.com使其可供contoso.comwww.contoso.com,和staging.www.contoso.comFor example, setting the cookie domain to .contoso.com makes it available to contoso.com, www.contoso.com, and staging.www.contoso.com.
CookieHttpOnlyCookieHttpOnly 指示是否 cookie 应只允许到服务器可访问的标志。A flag indicating if the cookie should be accessible only to servers. 此值更改为false允许客户端脚本访问 cookie,并可能会打开 cookie 被盗应用应您的应用程序具有跨站点脚本 (XSS)漏洞。Changing this value to false permits client-side scripts to access the cookie and may open your app to cookie theft should your app have a Cross-site scripting (XSS) vulnerability. 默认值为 trueThe default value is true.
CookiePathCookiePath 用于隔离同一主机名上运行的应用。Used to isolate apps running on the same host name. 如果必须在运行的应用/app1并且想要将 cookie 限制为该应用,设置CookiePath属性设置为/app1If you have an app running at /app1 and want to restrict cookies to that app, set the CookiePath property to /app1. 通过此操作,cookie 是仅可在请求上/app1和其下的任何应用。By doing so, the cookie is only available on requests to /app1 and any app underneath it.
CookieSecureCookieSecure 一个标志,指示是否创建的 cookie 应限制为 HTTPS (CookieSecurePolicy.Always),HTTP 或 HTTPS (CookieSecurePolicy.None),或与请求相同的协议 (CookieSecurePolicy.SameAsRequest)。A flag indicating if the cookie created should be limited to HTTPS (CookieSecurePolicy.Always), HTTP or HTTPS (CookieSecurePolicy.None), or the same protocol as the request (CookieSecurePolicy.SameAsRequest). 默认值为 CookieSecurePolicy.SameAsRequestThe default value is CookieSecurePolicy.SameAsRequest.
说明Description 有关提供给应用程序的身份验证类型的其他信息。Additional information about the authentication type which is made available to the app.
ExpireTimeSpanExpireTimeSpan TimeSpan后将身份验证票证到期。The TimeSpan after which the authentication ticket expires. 它被添加到当前时间来创建票证的到期时间。It's added to the current time to create the expiration time for the ticket. 若要使用ExpireTimeSpan,则必须设置IsPersistenttrueAuthenticationProperties传递给SignInAsyncTo use ExpireTimeSpan, you must set IsPersistent to true in the AuthenticationProperties passed to SignInAsync. 默认值为 14 天。The default value is 14 days.
SlidingExpirationSlidingExpiration 一个标志,指示 cookie 的到期日期重置多个的下半部分ExpireTimeSpan经过一段时间。A flag indicating whether the cookie expiration date resets when more than half of the ExpireTimeSpan interval has passed. 向前移动新的过期时间为当前日期加上ExpireTimespanThe new expiration time is moved forward to be the current date plus the ExpireTimespan. 绝对 cookie 到期时间可以通过使用设置AuthenticationProperties类调用时SignInAsyncAn absolute cookie expiration time can be set by using the AuthenticationProperties class when calling SignInAsync. 绝对过期时间可以通过限制身份验证 cookie 是有效的时间量来提高您的应用程序的安全性。An absolute expiration time can improve the security of your app by limiting the amount of time that the authentication cookie is valid. 默认值为 trueThe default value is true.

设置CookieAuthenticationOptionsCookie 身份验证中间件中Configure方法:Set CookieAuthenticationOptions for the Cookie Authentication Middleware in the Configure method:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    ...
});

Cookie 策略中间件使应用程序中的 cookie 策略功能。Cookie Policy Middleware enables cookie policy capabilities in an app. 到应用程序处理管道添加中间件是顺序敏感;它只影响在管道中注册后的组件。Adding the middleware to the app processing pipeline is order sensitive; it only affects components registered after it in the pipeline.

app.UseCookiePolicy(cookiePolicyOptions);

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

属性Property 描述Description
HttpOnlyHttpOnly 会影响是否 cookie 必须 HttpOnly,该值一个标志,指示是否 cookie 应只允许到服务器可访问。Affects whether cookies must be HttpOnly, which is a flag indicating if the cookie should be accessible only to servers. 默认值为 HttpOnlyPolicy.NoneThe default value is HttpOnlyPolicy.None.
MinimumSameSitePolicyMinimumSameSitePolicy 影响的 cookie 的同一站点属性 (见下文)。Affects the cookie's same-site attribute (see below). 默认值为 SameSiteMode.LaxThe default value is SameSiteMode.Lax. 此选项仅供 ASP.NET Core 2.0 +。This option is available for ASP.NET Core 2.0+.
OnAppendCookieOnAppendCookie 当会追加一个 cookie 时调用。Called when a cookie is appended.
OnDeleteCookieOnDeleteCookie 当删除 cookie 时调用。Called when a cookie is deleted.
SecureSecure 会影响是否 cookie 必须是安全。Affects whether cookies must be Secure. 默认值为 CookieSecurePolicy.NoneThe default value is CookieSecurePolicy.None.

MinimumSameSitePolicy (ASP.NET Core 2.0 + 仅)MinimumSameSitePolicy (ASP.NET Core 2.0+ only)

默认值MinimumSameSitePolicy值是SameSiteMode.Lax允许 OAuth2 身份验证。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 your setting of Cookie.SameSite in CookieAuthenticationOptions settings according to the matrix below.

MinimumSameSitePolicyMinimumSameSitePolicy Cookie.SameSiteCookie.SameSite 最终的 Cookie.SameSite 设置Resultant Cookie.SameSite setting
SameSiteMode.NoneSameSiteMode.None SameSiteMode.NoneSameSiteMode.None
SameSiteMode.LaxSameSiteMode.Lax
SameSiteMode.StrictSameSiteMode.Strict
SameSiteMode.NoneSameSiteMode.None
SameSiteMode.LaxSameSiteMode.Lax
SameSiteMode.StrictSameSiteMode.Strict
SameSiteMode.LaxSameSiteMode.Lax SameSiteMode.NoneSameSiteMode.None
SameSiteMode.LaxSameSiteMode.Lax
SameSiteMode.StrictSameSiteMode.Strict
SameSiteMode.LaxSameSiteMode.Lax
SameSiteMode.LaxSameSiteMode.Lax
SameSiteMode.StrictSameSiteMode.Strict
SameSiteMode.StrictSameSiteMode.Strict SameSiteMode.NoneSameSiteMode.None
SameSiteMode.LaxSameSiteMode.Lax
SameSiteMode.StrictSameSiteMode.Strict
SameSiteMode.StrictSameSiteMode.Strict
SameSiteMode.StrictSameSiteMode.Strict
SameSiteMode.StrictSameSiteMode.Strict

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

创建ClaimsIdentity包含任何必需声明s 和调用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以登录用户:Call SignInAsync to sign in the user:

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

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

事实上,使用的加密是 ASP.NET Core数据保护系统。Under the covers, the encryption used is ASP.NET Core's Data Protection system. 如果托管应用在多台计算机、 负载平衡跨应用程序,或使用 web 场,则必须配置数据保护使用相同密钥环和应用程序标识符。If you're hosting app on multiple machines, load balancing across apps, or using a web farm, then you must configure data protection to use the same key ring and app identifier.

注销Sign out

若要注销当前用户,然后删除其 cookie,调用SignOutAsync:To sign out the current user and delete their cookie, call SignOutAsync:

await HttpContext.SignOutAsync(
    CookieAuthenticationDefaults.AuthenticationScheme);

若要注销当前用户,然后删除其 cookie,调用SignOutAsync:To sign out the current user and delete their cookie, call SignOutAsync:

await HttpContext.Authentication.SignOutAsync(
    CookieAuthenticationDefaults.AuthenticationScheme);

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

对后端更改做出响应React to back-end changes

一旦创建了 cookie,它将成为标识的单个来源。Once a cookie is created, it becomes the single source of identity. 即使在后端系统中禁用用户,cookie 身份验证系统不了解,并且用户保持登录状态,只要其 cookie 有效。Even if you disable a user in your back-end systems, the cookie authentication system has no knowledge of this, and a user stays logged in as long as their cookie is valid.

ValidatePrincipal中 ASP.NET Core 事件 2.x 或ValidateAsync中 ASP.NET Core 1.x 可用来截获和重写的 cookie 身份验证方法。The ValidatePrincipal event in ASP.NET Core 2.x or the ValidateAsync method in ASP.NET Core 1.x can be used to intercept and override validation of the cookie identity. 此方法可减轻已吊销的用户访问应用的风险。This approach 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 has been changed. 如果数据库未已发生更改,因为发布用户的 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值。To implement this scenario, the database, which is implemented in IUserRepository for this example, stores a LastChanged value. 在数据库中,更新的任何用户时LastChanged值设置为当前时间。When any user is updated in the database, the LastChanged value is set to the current time.

为了使 cookie 无效时的数据库更改基于LastChanged值时,请创建与 cookieLastChanged包含当前声明LastChanged值位于数据库中:In 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事件,编写一个方法具有以下签名在从派生类中CookieAuthenticationEvents:To implement an override for the ValidatePrincipal event, write a method with the following signature in a class that you derive from CookieAuthenticationEvents:

ValidatePrincipal(CookieValidatePrincipalContext)

示例如下所示:An example looks like the following:

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 服务注册期间注册的事件实例ConfigureServices方法。Register the events instance during cookie service registration in the ConfigureServices method. 提供的作用域内的服务注册你CustomCookieAuthenticationEvents类:Provide a scoped service registration for your CustomCookieAuthenticationEvents class:

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

services.AddScoped<CustomCookieAuthenticationEvents>();

若要实现的替代ValidateAsync事件,编写一个方法具有以下签名:To implement an override for the ValidateAsync event, write a method with the following signature:

ValidateAsync(CookieValidatePrincipalContext)

ASP.NET Core 标识作为的一部分实现这一检查其SecurityStampValidatorASP.NET Core Identity implements this check as part of its SecurityStampValidator. 示例如下所示:An example looks like the following:

public static class LastChangedValidator
{
    public static async Task ValidateAsync(CookieValidatePrincipalContext context)
    {
        // Pull database from registered DI services.
        var userRepository = 
            context.HttpContext.RequestServices
                .GetRequiredService<IUserRepository>();
        var userPrincipal = context.Principal;

        // Look for the last changed 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 身份验证配置期间注册事件Configure方法:Register the event during cookie authentication configuration in the Configure method:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    Events = new CookieAuthenticationEvents
    {
        OnValidatePrincipal = LastChangedValidator.ValidateAsync
    }
});

请考虑在其中更新用户的名称的情况下—不会影响任何方式的安全决策。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. 这可能导致应用程序对较大性能产生负面影响。This 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 login 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.

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

AuthenticationProperties类驻留在Microsoft.AspNetCore.Authentication命名空间。The AuthenticationProperties class resides in the Microsoft.AspNetCore.Authentication namespace.

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

AuthenticationProperties类驻留在Microsoft.AspNetCore.Http.Authentication命名空间。The AuthenticationProperties class resides in the Microsoft.AspNetCore.Http.Authentication namespace.

可以设置使用绝对到期时间ExpiresUtcYou can set an absolute expiration time with ExpiresUtc. 若要创建持久 cookie,则还必须设置IsPersistent; 否则为 cookie 使用基于会话的生存期内创建,并且可能会到期之前或身份验证票证后它将保持。To create a persistent cookie, you must also set IsPersistent; otherwise, the cookie is created with a session-based lifetime and could expire either before or after the authentication ticket that it holds. ExpiresUtc上设置SignInAsync,它将重写的值ExpireTimeSpan的选项CookieAuthenticationOptions,如果设置。When ExpiresUtc is set on SignInAsync, 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.

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

其他资源Additional resources