【问题标题】:Hashing Password fails哈希密码失败
【发布时间】:2018-10-19 20:09:54
【问题描述】:

我正在尝试向我的 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();

【问题讨论】:

  • 您的 User 类是什么样的,特别是 Password 属性?另外,如何添加新用户?注册期间执行哈希的函数是什么?
  • @mcbowes 查看更新

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


【解决方案1】:

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

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

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

其中一个重载:

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

更新 1:

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

相反,您应该使用 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&lt;ApplicationUser&gt;


更新 2:

要在 ASP.NET Core 中使用 UserManager,您需要 inject it into your controller

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

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

然后你应该使用_userManager 实例。

在 Startup.cs 中找到名为 ConfigureServices 的方法,并放入依赖注入所需的以下行

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

【讨论】:

  • 我很抱歉,因为我是核心新手,但这需要什么样的设置?我假设有一些数据库连接?
  • 嗨 @Pio,我刚刚更新了我的答案 - 请参阅我关于 PasswordPasswordHash User 类成员的注释
  • 好吧,是的,您的用户类与我的类没有什么不同。但我不明白这个用户管理器是从哪里来的,我猜它需要注入但我在哪里设置呢?比如数据库连接,它应该使用哪个用户类等等?
  • 现在我在某个地方,我的用户现在有了一个“真实”,谢谢你的指导
猜你喜欢
  • 2012-07-07
  • 1970-01-01
  • 2023-04-08
  • 2015-11-30
  • 2018-01-31
  • 2020-04-19
  • 2017-11-30
  • 1970-01-01
相关资源
最近更新 更多