6

is there any default implementation for password history? i'm trying to implement that feature on my project with identity so i have added password history table which contain password hashes. when user change password usermanager generate hash for password.

var passwordHash = _userManager.PasswordHasher.HashPassword(user, newPassword);

if this hash does not inserted in password history table it allow to change password otherwise return error

but the problem is each time when generating hash for the specific password it generate random hashes which cannot be compare also

var passwordHash = _userManager.PasswordHasher.HashPassword(user, newPassword);

hash differ from

_userManager.ResetPasswordAsync(user, request.Token, password);

generated password hash.

May be i'm trying to do this in wrong way. what was the mistake i have done implementing password history?

thanks

Gayan
  • 2,750
  • 5
  • 47
  • 88
  • It shouldn't generate random hashes. It should generate the same hash for the same password every time. Otherwise something is seriously broken. – user207421 Feb 14 '18 at 09:24
  • i tried with resetting same password hash continuously changing – Gayan Feb 14 '18 at 09:29
  • Then you did it wrong. Obviously. The same data should hash to the same hash every time. Otherwise it is all pointless. Post your erroneous code. – user207421 Feb 14 '18 at 10:27
  • @EJP is correct. If the same password didn't always produce the same hash, no one could ever login, as that's part of the authentication process. The password the user enters is hashed and then compared to the hashed password in the database (which is basically exactly the same process you'd follow for your validation). – Chris Pratt Feb 14 '18 at 17:21
  • Any updates? I've faced the same issue. `var newPasswordHash = _passwordHasher.HashPassword(user, password); var newPasswordHash1 = _passwordHasher.HashPassword(user, password);` Every row returns different value – managerger May 16 '18 at 15:22

1 Answers1

8

Different hashes every time - it's how default implementation IPasswordHasher works. Look at this answer for more details: https://stackoverflow.com/a/20622428/6104621.

So, for your implementation password history, you can either implement IPasswordHasher or just verify a new password with all stored passwords hashes using method

PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword);

Just for example:

var passAlreadyExist = user.UserHistory
                .Select(h => h.PasswordHash)
                .Distinct()
                .Any(hash =>
                {
                    var res = manager.PasswordHasher.VerifyHashedPassword(user, hash, password);
                    return res == PasswordVerificationResult.Success;
                });

where UserHistory - it's custom table with some user info like password, email, name...

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
likeamike
  • 81
  • 1
  • 3