Asp.net 无处不在的 mvc 身份 SecurityStamp 注销

Asp.net mvc identity SecurityStamp signout everywhere

我想做的是限制一个用户ID一次只能登录一台设备。例如,用户 ID "abc" 登录到他们的计算机。用户 ID "abc" 现在尝试从他们的 phone 登录。我想要发生的是终止他们计算机上的会话。

我正在使用 Asp.net mvc 身份成员身份并为此目的使用 SecurityStamp。这是我在 Account/Login 操作中的代码:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        var user = UserManager.FindByEmail(model.Email);
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        await UserManager.UpdateSecurityStampAsync(user.Id);

根据 UpdateSecurityStampAsync 方法文档说:为用户生成一个新的安全标记,用于 SignOutEverywhere 功能。但它不起作用。

如果您想在其他设备上启用 cookie 的即时失效,则每个请求都必须访问数据库以验证 cookie。为此,您需要在 Auth.Config.cs 中配置 cookie 失效并将 validateInterval 设置为 0:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.             
        OnValidateIdentity = SecurityStampValidator
                .OnValidateIdentity<UserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromSeconds(0),
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }            
);