Search code examples
c#asp.net-core-2.0asp.net-core-identity

Change password in ASP.NET Core 2.x


How to change user password by admin in Asp core 2.x ?

or Change password with sms code

My sample code:

if (!ModelState.IsValid)
    return View(model);

var user = await _userManager.FindByNameAsync(model.UserName);
if (user == null)
    return RedirectToAction("Index");

if (model.smsCode == user.SmsCode)
{
    user.PasswordHash = model.NewPassword;

    IdentityResult result = await _userManager.UpdateAsync(user);
    if (result.Succeeded)
    {
    }
}

error: save unhash pass in db


Solution

  • We should not update the user.PasswordHash with a plain text , we should use Hash instead .

            var user = await _userManager.FindByNameAsync(model.UserName);
            if(user == null){ /**/ }
            if (model.smsCode != user.SmsCode){ /**/}
    
            // compute the new hash string
            var newPassword = _userManager.PasswordHasher.HashPassword(user,newpass);
            user.PasswordHash = newPassword;
            var res = await _userManager.UpdateAsync(user);
    
            if (res.Succeeded) {/**/}
            else { /**/}