我正在尝试向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; }
}
当前init只是一个管理员用户:
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();
答案 0 :(得分:1)
在我的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:
要在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>>();