I need ability to change password for user by admin. So, admin should not enter a current password of user, he should have ability to set a new password. I look at ChangePasswordAsync method, but this method requires to enter old password. So, this method is not appropriate for this task. Therefore I have made it by the following way:
[HttpPost]
public async Task<ActionResult> ChangePassword(ViewModels.Admin.ChangePasswordViewModel model)
{
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var result = await userManager.RemovePasswordAsync(model.UserId);
if (result.Succeeded)
{
result = await userManager.AddPasswordAsync(model.UserId, model.Password);
if (result.Succeeded)
{
return RedirectToAction("UserList");
}
else
{
ModelState.AddModelError("", result.Errors.FirstOrDefault());
}
}
else
{
ModelState.AddModelError("", result.Errors.FirstOrDefault());
}
return View(model);
}
it works, but theoretically we can receive error on AddPasswordAsync method. So, old password will be removed but new is not set. It's not good. Any way to do it in "one transaction"? PS. I seen ResetPasswordAsync method with reset token, seems, it's more safe (because can't be unstable situation with user) but in any case, it does by 2 actions.
ApplicationUserManager
is the class generated by the ASP.NET Template.Which means, you can edit it and add any functionality it doesn't have yet. The UserManager class has a protected property named
Store
which stores a reference to theUserStore
class (or any subclass of it, depending on how you configured your ASP.NET Identity or if you use custom user store implementations, i.e. if you use different database engine like MySQL).The
UserManager
is nothing else than a wrapper to the underlyingUserStore
. Check outIUserPasswordStore
interface documentation at MSDN on available Methods.Edit: The
PasswordHasher
is also a public property of theUserManager
class, see interface definition here.Edit 2: Since some people naively believe, you can't do password validation this way, I've updated it. The
PasswordHasher
property is also a property ofUserManager
and its as simple as adding 2 lines of code to add password validation too (which wasn't an requirement of the original question though).