1、先使用UserManager.RemovePassword(UserID),清空密码,再使用UserMnager.AddPassword(UserId,newPassword)增加新密码。
mvc中:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangePassword(ChangePasswordViewModel userViewModel)
{
var userId = User.Identity.GetUserId();
var _user = UserManager.FindById(userId);
if (ModelState.IsValid)
{
if (UserManager.CheckPassword(_user, userViewModel.OldPassword)) //UserManager.CheckPasswrod检查 密码是否正确。
{
UserManager.RemovePassword(userId); //清空旧密码。
UserManager.AddPassword(userId, userViewModel.NewPassword); //加入新密码.
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "输入的旧密码不正确");
return View(userViewModel);
}
}
else
{
ModelState.AddModelError("", "绑定失败");
return View(userViewModel);
}
}
webapi中
[Route("changerPasswordAdmin")]//更新用户密码
[HttpPost]
public async Task<ActionResult> ChangePasswordAsync(string userid,string NewPassword)
{
ApplicationUser user = (ApplicationUser)await _userManager.FindByIdAsync(userid);
await _userManager.RemovePasswordAsync(user); //清空旧密码。
var result = await _userManager.AddPasswordAsync(user,NewPassword); //加入新密码.
if (result.Succeeded)
{
return Ok("更新成功");
}
else
{
return BadRequest(result);
}
}
2、利用UserManager.GerneratePasswordResetTokeno为用户创建一个重置密码的GUID值,然后调用 ResetPassword(UserId,GUID,newPassword)值重新创建密码;
mvc中
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeUserPassword(ResetPasswordViewModel _resetPasswordViewModel)
{
if (!ModelState.IsValid)
{
return View(_resetPasswordViewModel);
}
var _user = UserManager.FindByName(_resetPasswordViewModel.UserName);
if (_user == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var code =UserManager.GeneratePasswordResetToken(_user.Id); //为用户创建一个重置密码的GUID值
var result =UserManager.ResetPassword(_user.Id,code,_resetPasswordViewModel.Password); //重新创建密码;
if (result.Succeeded)
{
return RedirectToAction("Index");
}
return View();
}
3、直接使用 UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword) 方法验证旧密码和更改新密码。执行后的Identity Result 结果将由模型绑定的状态返回给视图。比如当前密码错误,密码的复杂度达不到要求等。
mvc中
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
return RedirectToAction("Index","Home");
}
AddErrors(result);
return View(model);
}
webapi中
[Route("changerPassword")]//更新用户密码
[HttpPost]
//[Authorize(AuthenticationSchemes = "Bearer")]
//[Authorize]
public async Task<IActionResult> Password(string id,string OldPassword,string NewPassword)
{
ApplicationUser user = (ApplicationUser)await _userManager.FindByIdAsync(id); //直接获取用户信息
var result = await _userManager.ChangePasswordAsync(user, OldPassword, NewPassword);
if (result.Succeeded)
{
return Ok("更新成功");
}
else {
return BadRequest(result);
}
}