我是Core的新手。我在Visual Studio中创建了一个ASP.NET Core Web应用程序(MVC),其中包含存储在app中的个人用户帐户。我在SQL Server中为应用程序创建了一个数据库,更新了连接字符串,并在NuGet控制台中运行了Update-Database。我想覆盖密码哈希函数,而是使用bcrypt哈希。我希望使用BCrypt-Core,BCrypt.Net - Next或Bcrypt-Official软件包。但是我不知道从那里去哪里以确保在生成密码和用户登录时覆盖哈希。我的猜测是我需要覆盖PasswordHasher但是我需要覆盖什么方法以及什么时候用户想登录?任何有关当前实施的建议/建议/链接将不胜感激!
创建一个名为BCryptPasswordHasher.cs的类
public class BCryptPasswordHasher<TUser> : PasswordHasher<TUser> where TUser : class
{
/// <summary>
/// Overrides instance of Microsoft.AspNetCore.Identity.PasswordHasher
/// </summary>
/// <param name="optionsAccessor"></param>
public BCryptPasswordHasher(IOptions<PasswordHasherOptions> optionsAccessor = null)
{
}
/// <summary>
/// Returns a hashed representation of the supplied password for the specified user.
/// </summary>
/// <param name="user"></param>
/// <param name="password"></param>
/// <returns></returns>
public override string HashPassword(TUser user, string password)
{
return BCrypt.Net.BCrypt.HashPassword(password);
}
/// <summary>
/// Returns a Microsoft.AspNetCore.Identity.PasswordVerificationResult indicating
// the result of a password hash comparison.
/// </summary>
/// <param name="user"></param>
/// <param name="hashedPassword">The hash value for a user's stored password.</param>
/// <param name="providedPassword"> The password supplied for comparison.</param>
/// <returns></returns>
public override PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)
{
if (hashedPassword == null) { throw new ArgumentNullException(nameof(hashedPassword)); }
if (providedPassword == null) { throw new ArgumentNullException(nameof(providedPassword)); }
if (BCrypt.Net.BCrypt.Verify(providedPassword, hashedPassword))
{
return PasswordVerificationResult.Success;
}
else
{
return PasswordVerificationResult.Failed;
}
}
}
在Startup.cs中 - 在添加AddIdentity之前
services.AddScoped<IPasswordHasher<ApplicationUser>, BCryptPasswordHasher<ApplicationUser>>();
感谢安德鲁·洛克(Andrew Lock)让我90%的路程。 https://andrewlock.net/migrating-passwords-in-asp-net-core-identity-with-a-custom-passwordhasher/