Logout User From all Browser When Password is changed

anand picture anand · Feb 5, 2016 · Viewed 8.3k times · Source

I have a Reset Password page: enter image description here

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

public ActionResult ResetPassword(ResetPassword model)
{
    ...
    return RedirectToAction("Logout");
}

When the user changes their password, they get Logged Out from the browser. However, if they are logged into another browser at the same time they remain logged in on the other browser.

I want to log out the user from all browsers they are logged into when they change their password.

Answer

Chris picture Chris · Mar 17, 2016

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<ApplicationUserManager, ApplicationUser>(
            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.