PasswordHasher始终无法验证

时间:2017-03-27 14:58:58

标签: c# asp.net-mvc asp.net-identity

我正在实施一项政策,其中密码无法重复使用并且具有适当的结构,但是我正在尝试解决如何针对PasswordHasher进行检查,我总是得到失败的匹配。 请帮忙...

        try
        {
            UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(context);
            UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store);
            ApplicationUser cUser = await store.FindByNameAsync(model.UserName);
            if (cUser == null)
            {
                ModelState.AddModelError("", "User ID is not correct, please check and try again.");
                return BadRequest(ModelState);
            }
            else
            {
                /// Need to check the new password is already entered recently
                DataController dataController = new DataController();

                string[] pwds = dataController.CheckIfNewPasswordSameAsLastFivePassword(model.UserName);

                if (pwds != null)
                {
                    foreach (string pwd in pwds)
                    {
                        PasswordVerificationResult result1 = UserManager.PasswordHasher.VerifyHashedPassword(pwd, model.UserIdentifier);

                        if (result1 == PasswordVerificationResult.Success)
                        {
                            ModelState.AddModelError("", "Please choose a password that you have not used before");
                            return BadRequest(ModelState);
                        }
                    }

                }
                //Send new password in model.UserIdentifier
                await store.SetPasswordHashAsync(cUser, UserManager.PasswordHasher.HashPassword(model.UserIdentifier));
                await store.UpdateAsync(cUser);
                ApplicationUser userdetails = new ApplicationUser();

                userdetails = dataController.GetUsersDetails(model.UserName);
                if (userdetails.Email != null)
                {
                    await ResetORForgotPasswordSendEmail(userdetails.FirstName, userdetails.UserName, userdetails.Email);
                }
            }
        }
        catch (Exception ex)
        {
            Logger.Error(ex.Message, ex);
        }

        return Ok();
    }

1 个答案:

答案 0 :(得分:1)

VerifyHashedPassword会将密码与用户的当前密码进行比较。你应该做的只是哈希新密码并做一个简单的字符串比较你的旧密码哈希列表:

if (pwds.Contains(UserManager.PasswordHasher.HashPassword(model.NewPassword)))
{
    ModelState.AddModelError("NewPassword", "You've used that password before.");
}