在.NET Core 2.0中实现bcrypt

时间:2018-02-02 22:37:45

标签: authentication hash .net-core bcrypt

我是Core的新手。我在Visual Studio中创建了一个ASP.NET Core Web应用程序(MVC),其中包含存储在app中的个人用户帐户。我在SQL Server中为应用程序创建了一个数据库,更新了连接字符串,并在NuGet控制台中运行了Update-Database。我想覆盖密码哈希函数,而是使用bcrypt哈希。我希望使用BCrypt-Core,BCrypt.Net - Next或Bcrypt-Official软件包。但是我不知道从那里去哪里以确保在生成密码和用户登录时覆盖哈希。我的猜测是我需要覆盖PasswordHasher但是我需要覆盖哪些方法&当用户想要登录时怎么办?任何有关当前实施的建议/建议/链接都将不胜感激!

1 个答案:

答案 0 :(得分:0)

创建一个名为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>>();

感谢安德鲁·洛克让我90%的路程。 https://andrewlock.net/migrating-passwords-in-asp-net-core-identity-with-a-custom-passwordhasher/