You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改ASP.NET Core 2.1中Identity.TwoFactorRememberMe Cookie过期时间?

修改ASP.NET Core 2.1中Identity TwoFactorRememberMe Cookie的过期时间

我刚好在ASP.NET Core 2.1环境下处理过完全一样的需求,默认14天的有效期确实不够灵活,下面是亲测有效的解决方案:

  • 首先找到Startup.cs中的ConfigureServices方法,在你配置Identity的代码段之后,添加针对TwoFactorRememberMe Cookie的专属配置:
// 保留你原有的Identity配置
services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// 配置TwoFactorRememberMe Cookie的过期时间
services.Configure<CookieAuthenticationOptions>(IdentityConstants.TwoFactorRememberMeScheme, options =>
{
    // 这里设置你需要的有效期,比如改成30天
    options.ExpireTimeSpan = TimeSpan.FromDays(30);
    // 可选:开启滑动过期,用户每次访问系统时自动延长Cookie有效期
    options.SlidingExpiration = true;
});
  • 关键说明:IdentityConstants.TwoFactorRememberMeScheme是ASP.NET Core Identity内置的、专门标记“记住2FA客户端”Cookie的Scheme名称,通过针对这个Scheme配置CookieAuthenticationOptions,就能精准覆盖默认的14天过期规则,而不会影响其他Identity相关Cookie的行为。

  • 验证方式:配置完成后,调用signInManager.TwoFactorSignInAsync并将rememberClient参数设为true,此时生成的Identity.TwoFactorRememberMe Cookie就会使用你设置的新有效期了。

这个方案完全适配ASP.NET Core 2.1版本,不会出现旧版本Identity配置方法失效的问题。

内容的提问来源于stack exchange,提问作者user1506481

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:44:48