Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 547
lvl3hdi Avatar asked Dec 02 '22 11:12

lvl3hdi


1 Answers

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 { /**/}
like image 175
itminus Avatar answered Jan 29 '23 09:01

itminus