c# - 哈希密码失败
问题描述
我正在尝试向我的 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();
解决方案
在我的 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>>();
推荐阅读
- javascript - Why is the ternary operator in the for...of statement not working?
- python - Python Egg 库文件引用同一包中的其他文件
- rest - 是否可以构建一个用于查询 HDFS 数据的 REST 接口?
- java - 如何修改读取向量以读取矩阵的正则表达式?
- java - Eclipse 将依赖项添加到另一个 Maven 项目的正确方法?
- python-3.x - How to pass more than one parameter to python map function?
- caching - 什么是好的 javascript 异步初始化/缓存模式?
- java - Spring boot @MockBean 疏远行为
- java - 将方法 .equalsOr() 添加到 String 类
- git - 获取最近推送的提交的 github URL