Back to: ASP.NET MVC Tutorial For Beginners and Professionals
How to Update User Password in ASP.NET Identity
In this article, I am going to discuss How to Update a User Password in ASP.NET Identity. Please read our previous article where we discussed How to Update and Delete a User Account in ASP.NET Identity.
Update a User Password in ASP.NET Identity
There are two ways to update the password of a user in ASP.NET Identity. They are as follows:
- Changing the password by requiring the current one (the old password).
- Resetting the password by using Forget Password.
Changing User Password by using Old Password:
In order to change the password of a user in ASP.NET Identity, we need to the ChangePassword method of the ApplicationUserManager instance.
The ChangePassword method is used to change the user’s password and returns the result of the operation as an IdentityResult object. The ChangePassword method of the ApplicationUserManager instance requires 3 parameters i.e. the user id, the current password, and the new password as follows.
IdentityResult result = UserManager.ChangePassword(model.UserId, model.CurrentPassword, model.NewPassword);
You can also use the async version of the ChangePassword method as follows:
IdentityResult result =await UserManager.ChangePasswordAsync(model.UserId, model.CurrentPassword, model.NewPassword);
The ChangePassword method is called by the ApplicationUserManager instance which is responsible for performing the user-related operations. In this case, it is going to change or update the user password.
UserManager in ASP.NET Identity:
We use the GetUserManager method to get the ApplicationUserManager instance from the OWIN context as follows.
ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
We use the ApplicationUserManager instance instead of the UserManager instance in order to use the default validation logic for usernames and passwords which are configured in Create method of the IdentityConfig.cs file.
Namespaces:
In order to use the GetUserManager method, the ChangePassword method or ChangePasswordAsync method, and the IdentityResult object, we have to include the following namespaces:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
Note: If you go to the Manage Controller class, then you will see that the ChangePassword action methods are already implemented as shown in the below image to provide the Change Password Functionality.
If you are creating from scratch and if you don’t have the Manage Controller, then we can also implement the Change Password functionality using ASP.NET Identity. Let us see how we can do this.
Creating the ChangeUserPasswordViewModel:
Create a class file with the name ChangeUserPasswordViewModel.cs within the Models folder and then copy and paste the following code. You can give any name to your model and you can store the model anywhere in your project. But we are following the standard naming convention, as this model is created for the Change Password, so we are providing the name as ChangeUserPasswordViewModel, but it is not mandatory.
using System.ComponentModel.DataAnnotations; namespace AspNetIdentityWithNewProject.Models { public class ChangeUserPasswordViewModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
The ChangeUserPasswordViewModel object is the ViewModel that we are using in order to render and validate the ChangePassword view. The following HTTPPost action method is going to update the password of a user. I am not going to create the HTTP Get method and corresponding view and I am giving this as a task to you. You can refer to the existing View and existing HTTP get method of the Manage controller to change the password.
[HttpPost] public ActionResult ChangePassword(ChangeUserPasswordViewModel model) { if (ModelState.IsValid) { //Create an Instance of ApplicationUserManager ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); //Then Fetch the Logged In User Detail Based on User ID //User.Identity.GetUserId() Will give you the current logged in user id ApplicationUser user = UserManager.FindById(User.Identity.GetUserId()); //ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { //If The User Exists Then Change the Password IdentityResult result = UserManager.ChangePassword(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (result.Succeeded) { //After Successful Password Change, you can also sign-in the user and redirect to the Home Page user = UserManager.FindById(User.Identity.GetUserId()); //user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { ApplicationSignInManager SignInManager = HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); SignInManager.SignIn(user, isPersistent: false, rememberBrowser: false); //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } //Redirect to the Home Page return RedirectToAction("Index", "Home"); } //If Failure, add the Errors into the Model foreach (string error in result.Errors) { ModelState.AddModelError("", error); } //Return to the Change Password View and Show the Error Details return View(model); } //If the User Not Found, then display HttpNotFound Error return HttpNotFound(); } //If any Validation error, then stay in the same Change Password View and Show the Error Details return View(model); }
In the code above, we obtain all the necessary information to update a user’s password using an HTTP Post request. Firstly, we retrieve the user manager from the OWIN context by utilizing the GetUserManager method. Then, we locate the user to update by their ID with the FindById method. If the user does not exist, we display an HTTP 404 error page. Otherwise, we modify their password using the ChangePassword method and verify the operation’s success by accessing the Succeeded property of the IdentityResult object. If the operation was unsuccessful, we iterate through the Errors list and append them to the ModelState object with the AddModelError method. If the password change was successful, we may choose to log in to the user and redirect them to the home page.
In the next article, I am going to discuss How to Reset a User Password using Forgot Password in ASP.NET Identity. Here, in this article, I try to explain How to Update a User Password in ASP.NET Identity. I hope you enjoy this How to Update User Password in ASP.NET Identity article.
ha ha ha .. you are nothing……………
why it awaiting moderation.?????????