我正在使用带有 Asp.Identity 和两因素身份验证的 MVC5.2 的最新示例代码。
启用 2FA 后,当用户登录时,系统会提示输入代码(通过电话或电子邮件发送),并且他们可以选择“记住浏览器”,这样他们就不会在该浏览器上再次要求输入代码。
这是在VerifyCode操作中处理的
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
注意model.RememberMe
未在默认模板中使用,因此为 false。
我发现当我这样做时.AspNet.TwoFactorRememberBrowser
已设置,在会话结束时过期(因此它不记得浏览器)
现在如果我设置isPersistent = true
, .AspNet.TwoFactorRememberBrowser
有效期为 30 天,这很好,但是.AspNet.ApplicationCookie
还有 30 天的有效期 - 这意味着当我关闭浏览器并重新打开时,我会自动登录。
我希望它不会保留我的登录信息,但会保留我选择记住 2FA 代码的方式。也就是说,用户应该始终需要登录,但如果他们已经保存了 2fa 代码,则不应要求他们提供该代码。
有其他人看过这个吗,还是我错过了什么?
这段代码似乎并不是为了在同一请求/响应中设置多个身份 cookie 而设计的,因为 OWIN cookie 处理程序最终共享相同的 AuthenticationProperties。这是因为 AuthenticationResponseGrant 有一个主体,但主体可以有多个身份。
您可以通过更改然后恢复特定于 2FA cookie 提供程序的 ResponseSignIn 和 ResponseSignedIn 事件中的 AuthenticationProperties 来解决此错误:
//Don't use this.
//app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
//Set the 2FA cookie expiration and persistence directly
//ExpireTimeSpan and SlidingExpiration should match the Asp.Net Identity cookie setting
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie,
AuthenticationMode = AuthenticationMode.Passive,
CookieName = DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie,
ExpireTimeSpan = TimeSpan.FromHours(2),
SlidingExpiration = true,
Provider = new CookieAuthenticationProvider
{
OnResponseSignIn = ctx =>
{
ctx.OwinContext.Set("auth-prop-expires", ctx.Properties.ExpiresUtc);
ctx.OwinContext.Set("auth-prop-persist", ctx.Properties.IsPersistent);
var issued = ctx.Properties.IssuedUtc ?? DateTimeOffset.UtcNow;
ctx.Properties.ExpiresUtc = issued.AddDays(14);
ctx.Properties.IsPersistent = true;
},
OnResponseSignedIn = ctx =>
{
ctx.Properties.ExpiresUtc = ctx.OwinContext.Get<DateTimeOffset?>("auth-prop-expires");
ctx.Properties.IsPersistent = ctx.OwinContext.Get<bool>("auth-prop-persist");
}
}
});
确保设置与主 Asp.Net Identity cookie 相同的 ExpireTimeSpan 和 SldingExpiration 以保留这些设置(因为它们合并到 AuthenticationResponseGrant 中)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)