ASP.NET Identity 2.0: How to rehash password

半城伤御伤魂 提交于 2019-12-04 05:09:39

It seems rehashing mechanism is not implemented in the built-in user manager. But hopefully you could easily implemented. consider this:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    protected override async Task<bool> VerifyPasswordAsync(
          IUserPasswordStore<ApplicationUser, string> store, 
          ApplicationUser user, string password)
    {
        var hash = await store.GetPasswordHashAsync(user);
        var verifyRes = PasswordHasher.VerifyHashedPassword(hash, password);

        if (verifyRes == PasswordVerificationResult.SuccessRehashNeeded)
           await store.SetPasswordHashAsync(user, PasswordHasher.HashPassword(password));

        return verifyRes != PasswordVerificationResult.Failed;
    }
}

If you have implemented IPasswordHasher correctly, when returning a PasswordVerificationResult.SuccessRehashNeeded result, ASP.NET Core Identity will call the HashPassword method automatically for you, successfully authenticating the user and updating the hash in the database.

The class would look something like this:

public class PasswordHasherWithOldHashingSupport : IPasswordHasher<ApplicationUser>
{
    private readonly IPasswordHasher<ApplicationUser> _identityPasswordHasher;

    public PasswordHasherWithOldHashingSupport()
    {
        _identityPasswordHasher = new PasswordHasher<ApplicationUser>();
    }

    public string HashPassword(ApplicationUser user, string password)
    {
        return _identityPasswordHasher.HashPassword(user, password);
    }

    public PasswordVerificationResult VerifyHashedPassword(ApplicationUser user, string hashedPassword, string providedPassword)
    {
        var passwordVerificationResult = _identityPasswordHasher.VerifyHashedPassword(user, hashedPassword, providedPassword);

        if (passwordVerificationResult == PasswordVerificationResult.Failed)
        {
            /* Do your custom verification logic and if successful, return PasswordVerificationResult.SuccessRehashNeeded */
            passwordVerificationResult = PasswordVerificationResult.SuccessRehashNeeded;
        }

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