在没有 ASP.NET CoreIdentity的情况下使用cookie身份验证

作者:Rick Anderson

ASP.NET Core Identity是完整的、功能完备的身份验证提供程序,用于创建和维护登录名。 但是,可以使用没有 ASP.NET CoreIdentity的基于cookie的身份验证提供程序。 有关详细信息,请参阅 ASP.NET Core 上的 Identity 简介

查看或下载示例代码如何下载

若要在示例应用中进行演示,假设将用户 Maria Rodriguez 的用户帐户硬编码到该应用中。 使用电子邮件地址 maria.rodriguez@contoso.com 和任何密码以用户身份登录。 在Pages/Account/Login.cshtml.cs文件中使用AuthenticateUser方法对用户进行身份验证。 在实际示例中,用户将根据数据存储进行身份验证。

using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

builder.Services.AddHttpContextAccessor();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

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

app.MapRazorPages();
app.MapDefaultControllerRoute();

app.Run();

AuthenticationScheme传递给AddAuthentication以设置应用的默认身份验证方案。 当存在多个 cookie 身份验证实例并且应用需要使用特定方案进行授权时,AuthenticationScheme 很有用。 将AuthenticationScheme设置为CookieAuthenticationDefaults.AuthenticationScheme 会提供方案的"Cookies"值。 可以使用任何字符串值来区分该方案。

应用的身份验证方案不同于应用的 cookie 身份验证方案。 如果未向AddCookie提供cookie身份验证方案,它会使用CookieAuthenticationDefaults.AuthenticationSchemeCookieAuthenticationDefaults.AuthenticationScheme GitHub 源显示它设置为"Cookies"

默认情况下,身份验证cookie的IsEssential属性设置为true。 如果网站访问者未同意收集数据,则允许使用身份验证 cookie。 有关详细信息,请参阅 ASP.NET Core 中的一般数据保护条例 (GDPR) 支持

CookieAuthenticationOptions类用于配置身份验证提供程序选项。

使用AddCookie方法配置CookieAuthenticationOptions

using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        options.SlidingExpiration = true;
        options.AccessDeniedPath = "/Forbidden/";
    });

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

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

app.MapRazorPages();
app.MapDefaultControllerRoute();

app.Run();

Cookie策略中间件(GitHub 源)UseCookiePolicy启用cookie策略功能。 中间件按其添加顺序进行处理:

app.UseCookiePolicy(cookiePolicyOptions);

使用提供给Cookie策略中间件的CookiePolicyOptions以控制cookie处理的全局特性,并在附加或删除cookie时连接到cookie处理处理程序。

默认的MinimumSameSitePolicy值为SameSiteMode.Lax以允许 OAuth2 身份验证。 若要严格执行 SameSiteMode.Strict 的同一站点策略,请设置 MinimumSameSitePolicy。 尽管此设置会中断 OAuth2 和其他跨源身份验证方案,但它可提高不依赖跨源请求处理的其他类型应用的 cookie 安全级别。

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

根据下面的对照表,MinimumSameSitePolicy 的 Cookie 策略中间件设置会影响 CookieAuthenticationOptions 设置中的 Cookie.SameSite 设置。

MinimumSameSitePolicy Cookie.SameSite Resultant Cookie.SameSite setting
SameSiteMode.None SameSiteMode.None
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.None
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.Lax SameSiteMode.None
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.Lax
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.Strict SameSiteMode.None
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.Strict
SameSiteMode.Strict
SameSiteMode.Strict

要创建用于保存用户信息的 cookie,请构造一个 ClaimsPrincipal。 对用户信息进行序列化并将其存储在 cookie 中。

使用任何必需的 Claim 创建一个 ClaimsIdentity,并调用 SignInAsync 以登录该用户。 示例应用中的 Login.cshtml.cs 包含以下代码:

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    ReturnUrl = returnUrl;

    if (ModelState.IsValid)
    {
        // Use Input.Email and Input.Password to authenticate the user
        // with your custom authentication logic.
        //
        // For demonstration purposes, the sample validates the user
        // on the email address maria.rodriguez@contoso.com with 
        // any password that passes model validation.

        var user = await AuthenticateUser(Input.Email, Input.Password);

        if (user == null)
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }

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

        _logger.LogInformation("User {Email} logged in at {Time}.", 
            user.Email, DateTime.UtcNow);

        return LocalRedirect(Url.GetLocalUrl(returnUrl));
    }

    // Something failed. Redisplay the form.
    return Page();
}

若要查看翻译为非英语语言的代码注释,请在 此 GitHub 讨论问题中告诉我们。

SignInAsync 创建加密的 cookie 并将其添加到当前响应中。 如果未指定 AuthenticationScheme,则使用默认方案。

RedirectUri 默认只用于少数特定路径,例如登录路径和注销路径。 有关详细信息,请参阅CookieAuthenticationHandler 源

ASP.NET Core 的数据保护系统用于加密。 对于托管在多台计算机上的应用、跨应用进行负载均衡或使用 Web 场,请配置数据保护以使用相同的密钥链和应用标识符。

注销

要注销当前用户并删除他们的 cookie,请调用 SignOutAsync

public async Task OnGetAsync(string returnUrl = null)
{
    if (!string.IsNullOrEmpty(ErrorMessage))
    {
        ModelState.AddModelError(string.Empty, ErrorMessage);
    }

    // Clear the existing external cookie
    await HttpContext.SignOutAsync(
        CookieAuthenticationDefaults.AuthenticationScheme);

    ReturnUrl = returnUrl;
}

如果CookieAuthenticationDefaults.AuthenticationScheme"Cookies"未用作方案,请提供配置身份验证提供程序时使用的方案。 否则,使用默认方案。 例如,如果“ContosoCookie”用作方案,则提供配置身份验证提供程序时使用的方案。

当浏览器关闭时,它将自动删除基于会话的 cookie(非永久性 cookie),但在关闭单个标签页时不会清除任何 cookie。 服务器不会收到关于标签页或浏览器关闭事件的通知。

响应后端更改

创建 cookie 后,cookie 就是唯一的标识源。 如果在后端系统中禁用了用户帐户:

  • 应用的 cookie 身份验证系统将继续根据身份验证 cookie 处理请求。
  • 只要身份验证 cookie 有效,用户就会一直登录到该应用。

ValidatePrincipal事件可用于拦截和替代cookie标识的验证。 通过在每个请求上验证 cookie,可以降低已吊销用户访问应用的风险。

一种 cookie 验证方法是基于跟踪用户数据库何时更改。 如果自发布用户的 cookie 以来数据库未曾更改且他们的 cookie 仍然有效,则无需重新对用户进行身份验证。 在示例应用中,数据库在 IUserRepository 中实现并存储 LastChanged 值。 当用户在数据库中更新时,LastChanged 值设置为当前时间。

为了在数据库基于 LastChanged 值发生更改时使 cookie 无效,请使用包含数据库中当前 LastChanged 值的 LastChanged 声明创建 cookie:

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派生的类中编写具有以下签名的方法:

ValidatePrincipal(CookieValidatePrincipalContext)

以下是 CookieAuthenticationEvents 的示例实现:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
{
    private readonly IUserRepository _userRepository;

    public CustomCookieAuthenticationEvents(IUserRepository userRepository)
    {
        _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 服务注册期间注册事件实例。 为 CustomCookieAuthenticationEvents 类提供作用域内服务注册

using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();

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

builder.Services.AddScoped<CustomCookieAuthenticationEvents>();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

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

app.MapRazorPages();
app.MapDefaultControllerRoute();

app.Run();

考虑对用户名进行更新的情况,这个决定不会以任何方式影响安全性。 如果要以非破坏性的方式更新用户主体,请调用 context.ReplacePrincipal 并将 context.ShouldRenew 属性设置为 true

警告

此处介绍的方法将在每个请求上触发。 针对每个请求验证所有用户的身份验证 cookie 可能会导致应用性能大幅下降。

Persistent cookies

你希望 cookie 在整个浏览器会话中保持不变。 只有在用户显式同意并在登录时使用“记住我”复选框或类似机制的情况下,才能实现此永久性。

以下代码片段将创建在浏览器关闭后仍然保留的标识和相应的 cookie。 我们将遵守先前配置的任何可调到期设置。 如果浏览器关闭时 cookie 过期,则浏览器将在重启后清除 cookie。

AuthenticationProperties 中将 IsPersistent 设置为 true

// using Microsoft.AspNetCore.Authentication;

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

可以使用 ExpiresUtc 设置绝对过期时间。 若要创建永久性 cookie,还必须设置 IsPersistent。 否则,cookie 是使用基于会话的生存期创建的,并且可能在其保留的身份验证票证前后到期。 设置ExpiresUtc时,它会替代CookieAuthenticationOptionsExpireTimeSpan选项的值(如果已设置)。

以下代码段将创建持续 20 分钟的标识和相应的 cookie。 这将忽略以前配置的任何可调到期设置。

// 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 CoreIdentity的基于cookie的身份验证提供程序。 有关详细信息,请参阅 ASP.NET Core 上的 Identity 简介

查看或下载示例代码如何下载

若要在示例应用中进行演示,假设将用户 Maria Rodriguez 的用户帐户硬编码到该应用中。 使用电子邮件地址 maria.rodriguez@contoso.com 和任何密码以用户身份登录。 在Pages/Account/Login.cshtml.cs文件中使用AuthenticateUser方法对用户进行身份验证。 在实际示例中,用户将根据数据库进行身份验证。

配置

Startup.ConfigureServices方法中,使用AddAuthenticationAddCookie方法创建身份验证中间件服务:

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

AuthenticationScheme传递给AddAuthentication以设置应用的默认身份验证方案。 当存在多个 cookie 身份验证实例并且你想要使用特定方案进行授权时,AuthenticationScheme 很有用。 将AuthenticationScheme设置为CookieAuthenticationDefaults.AuthenticationScheme 可提供方案的 "Cookies" 值。 可提供任何字符串值来区分该方案。

应用的身份验证方案不同于应用的 cookie 身份验证方案。 如果未向AddCookie提供cookie身份验证方案,它会使用CookieAuthenticationDefaults.AuthenticationScheme ("Cookies")。

默认情况下,身份验证cookie的IsEssential属性设置为true。 如果网站访问者未同意收集数据,则允许使用身份验证 cookie。 有关详细信息,请参阅 ASP.NET Core 中的一般数据保护条例 (GDPR) 支持

Startup.Configure 中,调用 UseAuthenticationUseAuthorization 以设置 HttpContext.User 属性,并为请求运行授权中间件。 在调用 UseEndpoints 之前调用 UseAuthenticationUseAuthorization 方法:

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

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

CookieAuthenticationOptions类用于配置身份验证提供程序选项。

在服务配置中设置 CookieAuthenticationOptions,以在 Startup.ConfigureServices 方法中进行身份验证:

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

Cookie策略中间件启用cookie策略功能。 将中间件添加到应用处理管道要区分顺序,它只影响在管道中注册的下游组件。

app.UseCookiePolicy(cookiePolicyOptions);

使用提供给Cookie策略中间件的CookiePolicyOptions以控制cookie处理的全局特性,并在附加或删除cookie时连接到cookie处理处理程序。

默认的MinimumSameSitePolicy值为SameSiteMode.Lax以允许 OAuth2 身份验证。 若要严格执行 SameSiteMode.Strict 的同一站点策略,请设置 MinimumSameSitePolicy。 尽管此设置会中断 OAuth2 和其他跨源身份验证方案,但它可提高不依赖跨源请求处理的其他类型应用的 cookie 安全级别。

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

根据下面的对照表,MinimumSameSitePolicy 的 Cookie 策略中间件设置会影响 CookieAuthenticationOptions 设置中的 Cookie.SameSite 设置。

MinimumSameSitePolicy Cookie.SameSite Resultant Cookie.SameSite setting
SameSiteMode.None SameSiteMode.None
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.None
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.Lax SameSiteMode.None
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.Lax
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.Strict SameSiteMode.None
SameSiteMode.Lax
SameSiteMode.Strict
SameSiteMode.Strict
SameSiteMode.Strict
SameSiteMode.Strict

要创建用于保存用户信息的 cookie,请构造一个 ClaimsPrincipal。 对用户信息进行序列化并将其存储在 cookie 中。

使用任何必需的 Claim 创建一个 ClaimsIdentity,并调用 SignInAsync以用户身份登录:

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 讨论问题中告诉我们。

SignInAsync 创建加密的 cookie 并将其添加到当前响应中。 如果未指定 AuthenticationScheme,则使用默认方案。

RedirectUri 默认只用于少数特定路径,例如登录路径和注销路径。 有关详细信息,请参阅CookieAuthenticationHandler 源

ASP.NET Core 的数据保护系统用于加密。 对于托管在多台计算机上的应用、跨应用进行负载均衡或使用 Web 场,请配置数据保护以使用相同的密钥链和应用标识符。

注销

要注销当前用户并删除他们的 cookie,请调用 SignOutAsync

await HttpContext.SignOutAsync(
    CookieAuthenticationDefaults.AuthenticationScheme);

如果 CookieAuthenticationDefaults.AuthenticationScheme(或“Cookie”)未用作方案(例如,“ContosoCookie”),请提供配置身份验证提供程序时使用的方案。 否则,使用默认方案。

当浏览器关闭时,它将自动删除基于会话的 cookie(非永久性 cookie),但在关闭单个标签页时不会清除任何 cookie。 服务器不会收到关于标签页或浏览器关闭事件的通知。

响应后端更改

创建 cookie 后,cookie 就是唯一的标识源。 如果在后端系统中禁用了用户帐户:

  • 应用的 cookie 身份验证系统将继续根据身份验证 cookie 处理请求。
  • 只要身份验证 cookie 有效,用户就会一直登录到该应用。

ValidatePrincipal事件可用于拦截和替代cookie标识的验证。 通过在每个请求上验证 cookie,可以降低已吊销用户访问应用的风险。

一种 cookie 验证方法是基于跟踪用户数据库何时更改。 如果自发布用户的 cookie 以来数据库未曾更改且他们的 cookie 仍然有效,则无需重新对用户进行身份验证。 在示例应用中,数据库在 IUserRepository 中实现并存储 LastChanged 值。 当用户在数据库中更新时,LastChanged 值设置为当前时间。

为了在数据库基于 LastChanged 值发生更改时使 cookie 无效,请使用包含数据库中当前 LastChanged 值的 LastChanged 声明创建 cookie:

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派生的类中编写具有以下签名的方法:

ValidatePrincipal(CookieValidatePrincipalContext)

以下是 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.ConfigureServices 方法中注册事件实例。 为 CustomCookieAuthenticationEvents 类提供作用域内服务注册

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

services.AddScoped<CustomCookieAuthenticationEvents>();

考虑对用户名进行更新的情况,这个决定不会以任何方式影响安全性。 如果要以非破坏性的方式更新用户主体,请调用 context.ReplacePrincipal 并将 context.ShouldRenew 属性设置为 true

警告

此处介绍的方法将在每个请求上触发。 针对每个请求验证所有用户的身份验证 cookie 可能会导致应用性能大幅下降。

Persistent cookies

你希望 cookie 在整个浏览器会话中保持不变。 只有在用户显式同意并在登录时使用“记住我”复选框或类似机制的情况下,才能实现此永久性。

以下代码片段将创建在浏览器关闭后仍然保留的标识和相应的 cookie。 我们将遵守先前配置的任何可调到期设置。 如果浏览器关闭时 cookie 过期,则浏览器将在重启后清除 cookie。

AuthenticationProperties 中将 IsPersistent 设置为 true

// using Microsoft.AspNetCore.Authentication;

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

可以使用 ExpiresUtc 设置绝对过期时间。 若要创建永久性 cookie,还必须设置 IsPersistent。 否则,cookie 是使用基于会话的生存期创建的,并且可能在其保留的身份验证票证前后到期。 设置ExpiresUtc时,它会替代CookieAuthenticationOptionsExpireTimeSpan选项的值(如果已设置)。

以下代码段将创建持续 20 分钟的标识和相应的 cookie。 这将忽略以前配置的任何可调到期设置。

// using Microsoft.AspNetCore.Authentication;

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