Asp .Net Identity 2 - 密码更新后注销其他会话(使用安全戳)也会注销当前会话

mem*_*m27 6 c# asp.net asp.net-mvc owin asp.net-identity

当用户更改密码时,我需要立即使其无效并注销任何其他已登录的会话,但允许活动会话(刚刚更新其密码的用户)保持登录状态.

为此,我UpdateSecurityStampAsync(currentUser.Id);在UserManager上使用该方法.所有其他会话都已成功注销,但是SignInAsync在更新安全标记后调用后,活动会话也会被注销.

我正在使用的身份配置如下:

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)
});
Run Code Online (Sandbox Code Playgroud)

正在更新密码,更新安全标记以及据称将当前用户重新登录的控制器代码段是:

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);
Run Code Online (Sandbox Code Playgroud)

运行代码后,密码成功更新,并且由于更新了安全标记,所有会话都将被注销.但基于我见过的其他示例(如Chris的回答),上面的代码应刷新auth cookie并保持活动用户登录.

我尝试过以上代码的不同变体:

  • 在安全标记更新后将标志移出
  • 完全删除注销
  • 使用同步SignIn扩展方法而不是异步扩展方法

所有变体都会产生相同的结果:用户在更改密码后被迫重新登录.

是否存在配置错误或其他我忽略的内容?

编辑:我通过添加DefaultAuthenticationTypesSignOut调用中无意中修复了问题.

相关代码现在读作:

//updating the security stamp invalidates all other sessions
await _userManager.UpdateSecurityStampAsync(currentUser.Id);
_signInManager.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
await _signInManager.SignInAsync(currentUser, false, false);
Run Code Online (Sandbox Code Playgroud)

但是,如果有人能解释为什么认证类型在这种情况下很重要?

Hao*_*ung 1

不要将验证间隔设置为 TimeSpan.FromMinutes(0),因为这会导致立即发出登录 cookie,请将其设置为 1 秒之类的值。