要为双因素 cookie 设置自定义过期时间,看起来有两种不同的方法:
选项 1: 在services.AddAuthentication() 调用之后将以下内容放入您的启动中:
services.Configure<CookieAuthenticationOptions>
(IdentityConstants.TwoFactorRememberMeScheme, options =>
{
//this will override the default 14 day expire time
options.ExpireTimeSpan = TimeSpan.FromDays(30);
});
虽然您还应该考虑重命名 cookie 以隐藏信息 - 快速 google 搜索会通过查看默认 cookie 名称来显示您正在使用 asp.net 身份。这可以通过 Cookie.Name 属性同时更改:
services.Configure<CookieAuthenticationOptions>
(IdentityConstants.TwoFactorRememberMeScheme, o =>
{
//this will override the default cookie name for information hiding
o.Cookie.Name = "app.2fa.rememberme";
//this will override the default 14 day expire time to 30 days
o.ExpireTimeSpan = TimeSpan.FromDays(30);
});
选项 2:如果您将 AddIdentityCookies() 调用与 AddAuthentication() 调用一起使用,则可以更改名称和过期时间:
services.AddAuthentication().AddIdentityCookies(o =>
{
o.TwoFactorRememberMeCookie.Configure(a => a.Cookie.Name = "app.2fa.rememberme");
});
请注意,如果您还使用 Identity Server,选项 2 将不起作用,因为它会在 UseIdentityServer() 调用期间调用此选项。
作为参考,我通过查看身份测试了解了如何执行此操作:https://github.com/aspnet/Identity/blob/c7276ce2f76312ddd7fccad6e399da96b9f6fae1/test/Identity.Test/IdentityOptionsTest.cs#L77。这在我能找到的任何地方都没有记录,我很难最终弄清楚这一点。希望这有助于下一个来寻找如何做到这一点的人。
关于信息隐藏的主题 - 您可能还需要考虑重命名成功登录后代码验证期间使用的 TwoFactorUserId cookie。除了 IdentityConstant 略有不同之外,可以用相同的方式完成:
services.Configure<CookieAuthenticationOptions>
(IdentityConstants.TwoFactorUserIdScheme, options =>
{
options.Cookie.Name = "app.2fa.userid";
});
services.AddAuthentication().AddIdentityCookies(o =>
{
o.TwoFactorUserIdCookie.Configure(a => a.Cookie.Name = "app.2fa.userid");
});