Asp.net mvc identity SecurityStamp signout everywhere

时光怂恿深爱的人放手 提交于 2019-12-09 06:07:18

问题


What I want to do is to limit a user ID to only being able to log in to one device at a time. For example, user ID "abc" logs in to their computer. User ID "abc" now tries to log in from their phone. What I want to happen is to kill the session on their computer.

I'm using Asp.net mvc identity membership and using SecurityStamp for this purpose. This is my code in Account/Login action:

    [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);

According to the UpdateSecurityStampAsync method doc says : Generate a new security stamp for a user, used for SignOutEverywhere functionality. But it doesn't work.


回答1:


If you want to enable instant invalidation of cookies on other devices, then every request must hit the database to validate the cookie. To do that you need to configure cookie invalidation in Auth.Config.cs and set validateInterval to 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))
    }            
);


来源:https://stackoverflow.com/questions/36151800/asp-net-mvc-identity-securitystamp-signout-everywhere

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!