Reset Password in ASP.NET Core Identity with Email

How to implement Reset Password in ASP.NET Core Identity with Email? If this is your question you opened up the right post.

What is Reset Password?

If a user forgets the password, the User will input email address of login credentials and clicks on forget password. If the user exists in the database with the provided email, system will send a Reset Password email to the user with a link and link contains the specific token to reset password.

Reset/Forgot Password is the very basic and important feature/functionality of any website or portal. If it comes to ASP.NET Core Identity we are here to guide you. How simply you can implement this functionality into your ASP.NET Core Project. In this tutorial, I’m using the latest .NET Core Version 5 and my project is ASP.NET Core Web API. If you have not configured identity into your project you can follow our tutorial.

Tools:

Visual Studio Community

Windows OS

Let’s get started:

This is our API method for token generation and link building. In this method we are taking user’s email as an argument and finding the user with the email. If the user exists in database we will pass the user to the “GeneratePasswordResetTokenAsync(ApplicationUser)” . “GeneratePasswordResetTokenAsync(ApplicationUser)” this method will take the application user as an argument which user wants to reset the password. And generate a token for that specific user. After the Reset password token generation, we will create a link for our next API. That will confirm this forgot/reset password token and create a new password.

public async Task<ResponseViewModel<object>> SendResetPwdLink(string email)
{
   try
   {
      var user = await _userManager.FindByEmailAsync(email);
      var token = await _userManager.GeneratePasswordResetTokenAsync(user);
      var link = "https://localhost:44379/api/account/confirmresetpassword?";
      var buillink = link  + "&Id=" + user.Id + "&token=" + token;
      var emailtemplate = new EmailTemplate();
       emailtemplate.Link = buillink;
       emailtemplate.UserId = user.Id;
       emailtemplate.EmailType = EmailType.ResetPassword;
       var emailsent = _emailService.SendSmtpMail(emailtemplate);
       if(emailsent != true)
          throw new HttpStatusException(System.Net.HttpStatusCode.InternalServerError, "Email not sent.");

       return new ResponseViewModel<object>
       {
           Status = true,
           Message = "Link Sent Succesfully",
           StatusCode = System.Net.HttpStatusCode.OK.ToString(),
           Data = buillink
        };
   }
   catch (Exception e)
   {
       throw e;
    }
}

After generating the token we are building a link to confirm our generated token. And the link that we are building is for our next API that will confirm our token and update the password. We are also attaching the user Id. And token with the link as a query parameter so we can get the user and token into our confirm reset password API. After creating a proper link we are sending the link to our user email account. If you have not yet implemented an email sending service. Follow these tutorials For Gmail API and SMTP email services. Let’s move forward.

In the below method we are receiving three parameters as arguments. These are the arguments that we have added into our link in the above method. With the id we will find the specific user and pass it forward. To confirm our reset/forgot password token and update the new password. We will use “ResetPasswordAsync(ApplicationUser, string Token, string newPassword)“. It will take three arguments as a parameter Specific Identity user for whom we want to update the password. Reset Password Token and a new password that the user wants to update.

public async Task<ResponseViewModel<object>> ConfirmPwdLink(Guid id, string token, string newpassword)
 {
     var user = _context.Users.FirstOrDefault(s => s.Id == id);
     var result = await _userManager.ResetPasswordAsync(user, token, newpassword);
     if (!result.Succeeded)
     {
        return new ResponseViewModel<object>
        {
           Status = false,
           Message = "Invalid Request",
           StatusCode = System.Net.HttpStatusCode.UnprocessableEntity.ToString(),
        };
     }
    else
    {
       return new ResponseViewModel<object>
       {
           Status = true,
           Message = "Your Password has been succesfully updated",
           StatusCode = System.Net.HttpStatusCode.OK.ToString()
       };
    }
}

You will receive an email like this,

reset password in ASP.NET Core

Copy this link and paste it as it is in postman so you can add a new password to it. It will look like this and return the response true if our token will be successfully confirmed.

reset password in ASP.NET Core

I have also written a complete tutorial on email Confirmation with ASP.NET Core Identity.

Conclusion:

You can configure Reset/forgot password API by following these simple steps that we have mentioned above. if you face any issue or problem while configuring this method with your ASP.NET Core project feel free to comment below. We will try to respond ASAP.

Leave a Reply

Your email address will not be published.