Reputation: 415
I am new to developing with Core. I created a ASP.NET Core web application (MVC) in Visual Studio with Individual User accounts stored in app. I created a database for the app in SQL server, updated the connection string, and ran Update-Database in the NuGet console. I would like to override the password hashing function and instead use bcrypt to hash. I was hoping to use the BCrypt-Core, BCrypt.Net - Next, or Bcrypt-Official package. But I dont know where to go from there to ensure that the hashing is overridden when the password is generated and when the user logs in. My guess is that I need to override PasswordHasher but what methods do I need to override & what about when the user wants to log in? Any advice / suggestions / links to current implementations would be appreciated!
Upvotes: 2
Views: 6261
Reputation: 415
Create a class called 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;
}
}
}
In Startup.cs - BEFORE AddIdentity add
services.AddScoped<IPasswordHasher<ApplicationUser>, BCryptPasswordHasher<ApplicationUser>>();
Thanks to Andrew Lock for getting me 90% of the way there. https://andrewlock.net/migrating-passwords-in-asp-net-core-identity-with-a-custom-passwordhasher/
Upvotes: 2