I'm trying to add some basic authentication to my asp.net core website.
I have my users stored in a sqlite database and i'm trying to verify the password the user enters but for some reason it always fails even though the entered password is correct.
Any advise here?
This is my login action:
[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);
}
}
User:
[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; }
}
Current init just an admin user:
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();