首页 > 解决方案 > 哈希密码失败

问题描述

我正在尝试向我的 asp.net 核心网站添加一些基本身份验证。
我将我的用户存储在 sqlite 数据库中,我正在尝试验证用户输入的密码,但由于某种原因,即使输入的密码正确,它也总是失败。

这里有什么建议吗?

这是我的登录操作:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel ivm)
{
   if (ModelState.IsValid)
   {
      var user = _userRepo.Get(ivm.Email);
      if (user == null)
      {
         ModelState.AddModelError("UserError", "User not found");
         return View("Index", ivm);
      }
      PasswordHasher<User> hasher = new PasswordHasher<User>();
      var result = hasher.VerifyHashedPassword(user, user.Password, ivm.Password);
      if (result != PasswordVerificationResult.Failed)
      {
         string role = "";
         if (user.Role == Models.Enums.Role.Admin)
            role = "Admin";
         else
            role = "User";
         var claims = new[] { new Claim(ClaimTypes.Name, user.Id.ToString()), new Claim(ClaimTypes.Role, role) };
         var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
         await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
         return RedirectToAction("Index", "Home");
      }
      else
      {
         ModelState.AddModelError("PasswordError", "Wrong password");
         return View("Index", ivm);
      }
   }
   else
   {
      ModelState.AddModelError("ModelError", "ModelError");
      return View("Index", ivm);
   }
}

用户:

[Table("Users")]
public class User
{
    public string Email { get; set; }
    public string Password { get; set; }
    public Role Role { get; set; }
    public Guid Id { get; set; }
}

当前初始化只是一个管理员用户:

            var user = new User
            {
                Email = "email.com",
                Role = Models.Enums.Role.Admin,
                Id = Guid.NewGuid()
            };
            PasswordHasher<User> phw = new PasswordHasher<User>();
            string hashed = phw.HashPassword(user, "superpassword");
            user.Password = hashed;
            db.Users.Add(user);
            db.SaveChanges();

标签: c#asp.net-mvcasp.net-core

解决方案


在我的 ASP.NET Core 项目中,我使用UserManager它可以很好地处理密码检查

bool correctPassword = await _userManager.CheckPasswordAsync(user, password);

UserManager还可以处理用户创建,而无需处理密码哈希。

重载之一:

public virtual Task<IdentityResult> CreateAsync(TUser user, string password);

更新1:

根据您提供的代码,您将密码哈希分配给班级Password成员User

相反,您应该使用PasswordHash属性,例如

hostAdminUser = new ApplicationUser()
{
    UserName = SetupConsts.Users.Host.UserName,
    Email = SetupConsts.Users.Host.Email,
    EmailConfirmed = true,
    PasswordHash = new PasswordHasher<ApplicationUser>().HashPassword(hostAdminUser, SetupConsts.Users.Passwords.Default)
};

await _userManager.CreateAsync(hostAdminUser);

所以,这里是相关的位:PasswordHash = new PasswordHasher<ApplicationUser>


更新 2:

为了UserManager在 ASP.NET Core 中使用,您需要将其注入到您的控制器中

public class AuthController : Controller
{
    private UserManager<ApplicationUser> _userManager;

    public AuthController(
        UserManager<ApplicationUser> userManager
        )
    {
        _userManager = userManager;
    }

然后你应该使用_userManager实例。

在 Startup.cs 中找到调用的方法ConfigureServices,并将依赖注入所需的以下行

services.AddTransient<UserManager<ApplicationUser>>();


推荐阅读