Reputation: 203
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?
Upvotes: 4
Views: 1763
Reputation: 51
If you want to change your user's password you can try two kinds of approach. One approach can be using "RemovePassword" and "AddPassword" as below:
string pwd = txtpwd.Text.Trim();
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
string userName = UserName.Text;
var user = userManager.FindByName(userName);
if (user.PasswordHash != null)
{
userManager.RemovePassword(user.Id);
}
userManager.AddPassword(user.Id, pwd);
Another approach is using "ChangePassword" as below:
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
// var user = new IdentityUser() { UserName = UserName.Text };
if (UserName.Text != null && txtcurpwd != null && txtNewpwd != null)
{
string username = UserName.Text;
var user = userManager.FindByName(username);
IdentityResult result = userManager.ChangePassword(user.Id, txtcurpwd.Text, txtNewpwd.Text);
if (result.Succeeded)
lblErrorMsg.Text = "password changed successfully for the user : " + username;
else
lblErrorMsg.Text = result.Errors.FirstOrDefault();
}
else
lblErrorMsg.Text = "Details missing ";
}
Upvotes: 0
Reputation: 14741
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
}
}
Upvotes: 6