当用户更改密码时,我需要立即使所有其他已登录 session 失效并注销,但允许事件 session (刚刚更新密码的 session )保持登录状态。
为此,我在 UserManager 上使用 UpdateSecurityStampAsync(currentUser.Id);
方法。所有其他 session 均已成功注销,但尽管在更新安全标记后调用了 SignInAsync
,但事件 session 也已注销。
我使用的身份配置如下:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(0),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
},
CookieHttpOnly = true,
CookieSecure = CookieSecureOption.SameAsRequest,
SlidingExpiration = false,
ExpireTimeSpan = TimeSpan.FromMinutes(10)
});
正在更新密码、更新安全标记并假设当前用户重新登录的 Controller 代码片段是:
var updateResult = await _userManager.ChangePasswordAsync(currentUser.Id, form.CurrentPassword, form.NewPassword);
if (!updateResult.Succeeded)
{
//handle update failure
}
_signInManager.AuthenticationManager.SignOut();
//updating the security stamp invalidates all other sessions
await _userManager.UpdateSecurityStampAsync(currentUser.Id);
await _signInManager.SignInAsync(currentUser, false, false);
运行代码,密码已成功更新,并且由于更新了安全标记,所有 session 都已注销。但是根据我见过的其他例子(比如 answer from Chris ),上面的代码应该刷新 auth cookie 并保持事件用户登录。
我尝试了上述代码的不同变体:
- 将注销移动到安全标记更新之后
- 完全取消注销
- 使用同步
SignIn
扩展方法代替异步方法
所有变体都会产生相同的结果:用户在更改密码后被迫重新登录。
是否存在配置错误或其他我忽略的问题?
编辑:
我无意中通过将 DefaultAuthenticationTypes
添加到 SignOut
调用中解决了这个问题。
相关代码现在是:
//updating the security stamp invalidates all other sessions
await _userManager.UpdateSecurityStampAsync(currentUser.Id);
_signInManager.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
await _signInManager.SignInAsync(currentUser, false, false);
但是,是否有人可以解释为什么在这种情况下身份验证类型很重要?
最佳答案
不要将验证间隔设置为 TimeSpan.FromMinutes(0),因为这会导致立即发出登录 cookie,而是将其设置为类似 1 秒的值。
关于c# - Asp .Net Identity 2 - 在密码更新后注销其他 session (使用安全标记)也会注销当前 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43675904/