aspnet identity 避免同时登录同一个账号

aspnet identity avoid simultaneous login same account

我正在搜索,但找不到这个问题的答案:aspnet identity 是否提供了一种避免从同一帐户同时登录的方法?

Identity 没有内置的方法来跟踪同时登录,但您可以做一个解决方法:每次用户登录时,在设置 auth-cookie 之前,将用户的 SecurityStamp 更改为 await userManager.UpdateSecurityStampAsync(user.Id);

并确保您的 Startup.Auth.cs 中包含此部分:

        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<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(5),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });            

这样每次用户登录时,所有其他会话都将失效,因为用户的 SecurityStamp 已更改。并且 validateInterval 的值足够低,因此其他 auth-cookie 可以很快失效。