Reset Users Passwords with ASP.Net Identity

private void ChangePassword(string userId, string newPassword)
  //Get the user manager and user. (if the user is not found, user will be null)
  var manager = Context.GetOwinContext().GetUserManager();
  ApplicationUser user = manager.FindById(userId);

  //PasswordHash is just a string. You can set to any string value, and it won't cause an error.
  //It will just be challenging for the user to actually login.
  user.PasswordHash = manager.PasswordHasher.HashPassword(newPassword);

  //see below
  //save changes
  IdentityResult v = manager.Update(user);
  if (v.Succeeded)
    //failure. Perhaps Loop through v.Errors to find out why.
    //Though, the documentation doesn't provide any hints as to what possible values
    //v.Errors may contain (it's an IEnumerable)


This is part of the “Sign out everywhere” feature. If a user is logged into an app, and an admin changes their password or removes them from a role, any authentication tokens/cookies should be invalided. There are a couple pieces of code that make this happen. The first is while instantiating a new CookieAuthenticationProvider and the second is the “UpdateSecurityStamp”.

In web forms apps, theĀ  CookieAuthenticationProvider is configured in Startup.Auth.cs as follows:

Provider = new CookieAuthenticationProvider
  OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
  validateInterval: TimeSpan.FromMinutes(20),
  regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))

With the above configuration, consider the following:

1. User Logs in to site

2. Admin changes User’s password

3. 20 minutes after User logged in, the cookie expires and the system tries to renew it.

At this point, if the value of the cookie’s SecurityStamp matches the current security stamp in the database, then the cookie will be regenerated, and the user will be able to continue using the site without having to re-enter a password. If the SecurityStamp does not match, the user will be redirected to the login page and they will have to re-authenticate (generating a new cookie/token).

So, the properies of the CookieAuthenticationProvider tells the system to check the SecurityStamp. The UpdateSecurityStamp actually changes the SecurityStamp. If you reset the user’s password but don’t call UpdateSecurityStamp, the SecurityStamp will remain unmodified, and the user will not be prompted to re-authenticate based on the validationInterval.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s