Search code examples
asp.netasp.net-identity

Failed to change password with UserManager.RemovePassword() and UserManager.AddPassword() in Asp.Net Identity


I use the following code to change a user's password:

UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = userManager.FindByName(currentUser.LoginName); // currentUser is the currently logged in user
IdentityResult result1 = userManager.RemovePassword(user.Id);
IdentityResult result2 = userManager.AddPassword(user.Id, txtPassword1.Text);

It works last year. But this year when I run it, it doesn't work (exactly the same code). When it runs to this statement:

IdentityResult result1 = userManager.RemovePassword(user.Id);

it gives the following exception:

{"Cannot insert the value NULL into column 'PasswordHash', table 'xxx.dbo.AspNetUsers'; column does not allow nulls. UPDATE fails.The statement has been terminated."}

I debugged into into, right before that statement,

user.PasswordHash = 'AAdcuoWRRXqfkB+vWpemPCkFNgWRGGe2tXyeJHy21S8qYYfAo9wJbfqtkog+lk2dZg=='

but after this statement, user.PasswordHash becomes null

I am really confused. What's the problem here?


Solution

  • If you want change user password use this code instead:

    var validPass= await userManager.PasswordValidator.ValidateAsync(txtPassword1.Text);
    if(validPass.Succeeded)
    {
        var user = userManager.FindByName(currentUser.LoginName);
        user.PasswordHash = userManager.PasswordHasher.HashPassword(txtPassword1.Text);
        var res= userManager.Update(user);
        if(res.Succeeded)
        {
            // change password has been succeeded
        }
    }