如何修改ASP.NET Core 2.1中Identity.TwoFactorRememberMe Cookie过期时间?
我刚好在ASP.NET Core 2.1环境下处理过完全一样的需求,默认14天的有效期确实不够灵活,下面是亲测有效的解决方案:
- 首先找到
Startup.cs中的ConfigureServices方法,在你配置Identity的代码段之后,添加针对TwoFactorRememberMeCookie的专属配置:
// 保留你原有的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.TwoFactorRememberMeCookie就会使用你设置的新有效期了。
这个方案完全适配ASP.NET Core 2.1版本,不会出现旧版本Identity配置方法失效的问题。
内容的提问来源于stack exchange,提问作者user1506481
相关产品推荐
相关产品推荐

