如何禁用身份.net核心的自动哈希密码

时间:2017-05-29 13:41:09

标签: c# asp.net .net asp.net-core

我无法找到禁用身份.net核心的自动哈希密码的方法。 因为此代码会自动哈希密码:

var result = await _userManager.CreateAsync(user, model.Password);

2 个答案:

答案 0 :(得分:3)

您可以编写一个覆盖UserManager

的类
public class ApplicationUserManager : UserManager<IdentityUser>
{
    public ApplicationUserManager(IUserStore<IdentityUser> store)
        : base(store)
    {
        this.PasswordHasher = new CustomPasswordHasher();
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<IdentityUser>(context.Get<ApplicationDbContext>()));         

        manager.PasswordHasher = new CustomPasswordHasher();
    }
}

然后使用继承PasswordHasher的新自定义哈希类覆盖PasswordHasher

internal class CustomPasswordHasher : PasswordHasher
{
    public override string HashPassword(string password)
    {
        return password;
        //return Crypto.Sha1.Encrypt(password);
    }

    public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
    {
        //var testHash = Crypto.Sha1.Encrypt(providedPassword);
        return hashedPassword.Equals(testHash) || hashedPassword.Equals(providedPassword) ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed;
    }
}

最后,请记住,通过这样做,您将失去数据库用户的安全。

答案 1 :(得分:3)

由于Asp.NET Core MVC使用依赖注入来设置Identity,所以您只需创建密码哈希类的备用:

public class CustomPasswordHasher : IPasswordHasher<AppUser>
{
    public string HashPassword(AppUser user, string password)
    {
        return password;
    }

    public PasswordVerificationResult VerifyHashedPassword(AppUser user, string hashedPassword, string providedPassword)
    {
        return hashedPassword.Equals(providedPassword) ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed;
    }
}

并添加:

services.AddScoped<IPasswordHasher<AppUser>, CustomPasswordHasher>();

你mvc app statup.cs