Logout User From all Browser When Password is changed

后端 未结 6 1784
慢半拍i
慢半拍i 2020-12-14 09:17

I have a Reset Password page:

When the user fills the details and clicks the Reset Password button. The following controller is called:



        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 09:57

    I saw you are using ASP.NET Identity 2. What you are trying to do is already built in. All you need to do is change the SecurityStamp and all previous authentication cookies are no longer valid.

    After you change the password you also need to change the SecurityStamp:

    await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
    await UserManager.UpdateSecurityStampAsync(User.Identity.GetUserId());
    

    If you want the user to remain logged in, you have to reissue a new authentication cookie (signin):

        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
    

    Otherwise the user/session who initated the password change will also be logged out.

    And to log out all other sessions immediately you need to lower the check interval in the config:

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        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(
                validateInterval: TimeSpan.FromSeconds(1),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    });
    

    Steps to reproduce:

    1. Created a new Asp.Net Web App in VS2015.
    2. Choose MVC template.
    3. Edit App_Stat/Startup.Auth.cs, line 34: change validateInterval: TimeSpan.FromMinutes(30) to validateInterval: TimeSpan.FromSeconds(1)
    4. Edit Controllers/ManageController.cs, line 236: add the UserManager.UpdateSecurityStampAsync method call.
    5. Run project, create a user, login, open a different browser and also login.
    6. Change password, refresh the page in the other browser : you should be logged out.

提交回复
热议问题