Reputation: 48522
I have an MVC 5 Identity 2 app. I'm trying to change a user's password as follows:
public async Task<string> ChangePassword()
{
var user = await this.UserManager.FindByIdAsync(18);
PasswordHasher hasher = new PasswordHasher();
user.PasswordHash = hasher.HashPassword("NewPassword");
this.UserManager.Update(user);
return string.Empty;
}
this.UserManager is defined as:
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
The method executes successfully, but the password is not getting changed. Am I missing a step?
Upvotes: 2
Views: 385
Reputation: 68
I believe UserManager has this handy method:
public virtual Task<IdentityResult> ChangePasswordAsync(
TKey userId,
string currentPassword,
string newPassword
)
EDIT:
This seems to be working for me. A UserManager property is defined as such:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
Then, the password reset method:
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
Upvotes: 0
Reputation: 20413
UserManager has these methods to change user's passwords:
public virtual Task<IdentityResult> ResetPasswordAsync(TKey userId, string token, string newPassword)
public virtual Task<IdentityResult> ChangePasswordAsync(TKey userId, string currentPassword, string newPassword);
protected virtual Task<IdentityResult> UpdatePassword(IUserPasswordStore<TUser, TKey> passwordStore, TUser user, string newPassword);
Upvotes: 1