【发布时间】: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