比较数据库中的密码以进行密码更新

Compare Password from Database for Password Update

这就是我创建用户来为我的数据库做种的方式

if (!context.Users.Any())
{
    var userStore = new UserStore<ApplicationUser>(context);
    var userManager = new UserManager<ApplicationUser>(userStore);
    userManager.Create(user, "P@ssw0rd");
    context.AspNetUsersExtendedDetails.AddOrUpdate(userExtended);
    context.SaveChanges();

}

当我尝试像这样更新密码时出现问题:

var userStore = new UserStore<ApplicationUser>(dbContext);
var userManager = new UserManager<ApplicationUser>(userStore);

var currentPasswordHash = userManager.PasswordHasher.HashPassword(Input.CurrentPassword);
if(user.PasswordHash == currentPasswordHash)
{
    var passwordHash = userManager.PasswordHasher.HashPassword(Input.NewPassword);
    user.PasswordHash = passwordHash;
    dbContext.SaveChanges();
    logger.Info(AspNetEventLogs.Update + " Password updated for User: " + user.UserName);
}
else
{
    logger.Error(AspNetEventLogs.Error + " Current password incorrect");
}

我根本无法匹配哈希值。我用来创建用户和散列密码的方法是相似的。不知道我还能做什么。

如果您查看 PasswordHasher.HashPassword 的源代码,您会看到:

using (var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, PBKDF2IterCount))
{
    salt = deriveBytes.Salt;
    subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
}

因此,当您调用它时会生成一个新的盐和子密钥。这就是为什么您的支票永远不会(就已证明的而言)return true.

为了这个特定目的,PasswordHasher 有一个 VerifyHashedPassword 方法可以使用存储的 salt 和子键重新创建散列——这就是您使用身份登录时调用的方法。

但是请注意,出于安全目的,您的方法 lacks the update of the user's SecurityStamp 必须在密码更改时进行更新。

此外,请注意,您正在做的所有手动工作都已在 Identity 的核心库中考虑到,您所要做的就是调用 UserManager.UpdatePasswordAsync,它将在使用新密码之前检查密码提供。