如何禁用Identity .NET Core的自动哈希密码



我找不到禁用Identity .NET Core的自动哈希密码的方法。因为此代码会自动放大密码:

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

您可以编写覆盖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;
    }
}

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

因为ASP.NET Core MVC使用依赖注入来设置身份,您所需要的只是创建您的替代密码哈希类:

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;
    }
}

和add:

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

在您的MVC App Statup.cs

最新更新