4

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

2
  • 1
    The error tells you that the password needs to be hashed before saving. Saving cleartext passwords is a big no-no. Commented Aug 2, 2018 at 9:18
  • Are you trying to save a plain text password into the PasswordHash field? I would expect you would have to hash model.NewPassword before saving it Commented Aug 2, 2018 at 9:19

1 Answer 1

17

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 { /**/}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.