S
S
Sasha Pleshakov2016-10-10 19:12:10
ASP.NET
Sasha Pleshakov, 2016-10-10 19:12:10

How are passwords encrypted in ASP.NET MVC?

Created a method in the ApplicationUserManager class to search the database by email and password, because FindAsync searches by name and password, but it seems to me that ASP.NET Identity has a different hashing method (I use Crypto.HashPassword), because the method I use produces a different hash.

public async Task<ApplicationUser> FindByEmailAndPasswordAsync(string email, string password)
{
    ThrowIfDisposed();
    var passwordHash = Crypto.HashPassword(password);
    ApplicationUser user;
    using(var db = new ApplicationDbContext())
    {
        user = await db.Users.Where(u => u.Email == email && u.PasswordHash == passwordHash).FirstOrDefaultAsync();
    }
    if(user == null)
    {
        return null;
    }
    return user;
}

Moved to Login controller
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        PasswordHasher ph = new PasswordHasher();
        var passwordHash = ph.HashPassword(model.Password);
        ApplicationUser user;
        using (var db = new ApplicationDbContext())
        {
            user = await db.Users.Where(u => u.Email == model.Email && u.PasswordHash == passwordHash).FirstOrDefaultAsync();
        }
        if (user != null)
        {
        //дальше идет код контроллера, который создается автоматически

Answer the question

In order to leave comments, you need to log in

1 answer(s)
#
#algooptimize #bottize, 2016-10-10
@mnepoh

asp net identity
usermanager

protected virtual async Task<bool> VerifyPasswordAsync(IUserPasswordStore<TUser, TKey> store, TUser user, string password)
    {
      string hash = await store.GetPasswordHashAsync(user).WithCurrentCulture<string>();
      return this.PasswordHasher.VerifyHashedPassword(hash, password) != PasswordVerificationResult.Failed;
    }


 public virtual async Task<bool> CheckPasswordAsync(TUser user, string password)
    {
      this.ThrowIfDisposed();
      IUserPasswordStore<TUser, TKey> passwordStore = this.GetPasswordStore();
      if ((object) user == null)
        return false;
      return await this.VerifyPasswordAsync(passwordStore, user, password).WithCurrentCulture<bool>();
    }

I see no reason to duplicate the code, you can just use usermanager.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question