c# - Asp .Net Identity 2 - 在密码更新后注销其他 session (使用安全标记)也会注销当前 session

标签 c# asp.net asp.net-mvc asp.net-identity owin

当用户更改密码时,我需要立即使所有其他已登录 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/

相关文章:

c# - 如何使用下一个和上一个节点引用有效地对节点列表进行排序?

c# - 分离excel多行选择

c# - 使用 json 数组和 json 对象的优缺点

c# - 在 Repeater 中传递行的 ID 以提交 ASP NET 中的按钮

asp.net - Visual Studio 忽略 try catch - 仅调试

c# - 如何通过 'ESC' 按键导航到之前访问过的页面。 ASP.NET MVC(C#)

c# - 如何将 AjaxControlToolkit 添加到 Visual Studio 2013 web 表单模板?

c# - 代码隐藏文件无法识别 *.ascx 中的控件

c# - 将 Windsor CaSTLe 注入(inject)的依赖项传递给并行线程 - Dispose() 问题

asp.net-mvc - 无法加载文件或程序集 'System.Web.WebPages.Razor'?