Search code examples
c#asp.net-mvcasp.net-mvc-5

.NET MVC 5 Razor - check password is valid for logged in user Id


I need to check the user password before performing an action.

For example, the user tries to withdraw their credit. There are 2 inputs:

  1. Amount to be withdrawn
  2. User password

As the user already logged in, I am able to get the UserId. However, I need to validate their password against currently logged in UserId.

The easiest way is to force the user to log in again (ie. ask them to enter their username and password), but it looks silly and unnecessary.

Any idea how to validate user's password on particular user Id?

Thanks


Solution

  • I found the solution. It is actually very simple. First, is to get the user manager. If you don't know how to get user manager, simply follow the default example when creating MVC project. The code is:

    HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>()
    

    Here is the code:

    //var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    var user = userManager.Users.FirstOrDefault(rec => rec.Id == userId);
    return userManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, model.Password) != PasswordVerificationResult.Failed;
    

    That is it! I hope this post is helpful to someone facing a similar problem.

    Cheers!