如何使用自定义IPasswordHasher?

时间:2014-10-22 10:30:36

标签: c# asp.net asp.net-mvc asp.net-mvc-5

我实施了IPasswordHasher

public class MyPasswordHasher : IPasswordHasher
{
    public string HashPassword(string password)
    {
        using (SHA256 mySHA256 = SHA256Managed.Create())
        {
            byte[] hash = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(password.ToString()));

            StringBuilder hashSB = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                hashSB.Append(hash[i].ToString("x2"));
            }
            return hashSB.ToString();
        }
    }


    public PasswordVerificationResult VerifyHashedPassword(
      string hashedPassword, string providedPassword)
    {
        if (hashedPassword == HashPassword(providedPassword))
            return PasswordVerificationResult.Success;
        else
            return PasswordVerificationResult.Failed;
    }
}

我在IdentityConfig中写道

manager.PasswordHasher = new MyPasswordHasher();

但AccountController / Login中的var user = await UserManager.FindAsync(model.Email, model.Password);不使用MyPasswordHaser。

如何在身份2.1中使用它?

我的项目https://yadi.sk/d/NUL56SMccCtqd

2 个答案:

答案 0 :(得分:2)

您必须将其插入UserManager:

public class AppUserManager : UserManager<AppUser, int>
{
    public AppUserManager(AppUserStore a_store)
        : base(a_store)
    {
        _container = a_container;
        _emailService = _container.GetInstance<IEmailService>();

        PasswordHasher = new AppPasswordHasher();
    }
}

答案 1 :(得分:2)

使用:

PasswordHasher = new MyPasswordHasher(); 

在UserManager ctor!