How can I get the password of a user in the new ASP.NET Identity system? Or how can I reset without knowing the current one (user forgot password)?
Best way to Reset Password in Asp.Net Core Identity use for Web API.
Note* : Error() and Result() are created for internal use. You can return you want.
[HttpPost]
[Route("reset-password")]
public async Task<IActionResult> ResetPassword(ResetPasswordModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
try
{
if (model is null)
return Error("No data found!");
var user = await _userManager.FindByIdAsync(AppCommon.ToString(GetUserId()));
if (user == null)
return Error("No user found!");
Microsoft.AspNetCore.Identity.SignInResult checkOldPassword =
await _signInManager.PasswordSignInAsync(user.UserName, model.OldPassword, false, false);
if (!checkOldPassword.Succeeded)
return Error("Old password does not matched.");
string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
if (string.IsNullOrEmpty(resetToken))
return Error("Error while generating reset token.");
var result = await _userManager.ResetPasswordAsync(user, resetToken, model.Password);
if (result.Succeeded)
return Result();
else
return Error();
}
catch (Exception ex)
{
return Error(ex);
}
}
Create method in UserManager<TUser, TKey>
public Task<IdentityResult> ChangePassword(int userId, string newPassword)
{
var user = Users.FirstOrDefault(u => u.Id == userId);
if (user == null)
return new Task<IdentityResult>(() => IdentityResult.Failed());
var store = Store as IUserPasswordStore<User, int>;
return base.UpdatePassword(store, user, newPassword);
}
Or how can I reset without knowing the current one (user forgot password)?
If you want to change a password using the UserManager but you do not want to supply the user's current password, you can generate a password reset token and then use it immediately instead.
string resetToken = await UserManager.GeneratePasswordResetTokenAsync(model.Id);
IdentityResult passwordChangeResult = await UserManager.ResetPasswordAsync(model.Id, resetToken, model.NewPassword);
string message = null;
//reset the password
var result = await IdentityManager.Passwords.ResetPasswordAsync(model.Token, model.Password);
if (result.Success)
{
message = "The password has been reset.";
return RedirectToAction("PasswordResetCompleted", new { message = message });
}
else
{
AddErrors(result);
}
This snippet of code is taken out of the AspNetIdentitySample project available on github