Reset Passwords in ASP.NET 5 & Core Identity - The Guide

Updated on 22nd November 2020

When building a web application with authentication, you'll need some way to reset user's passwords at some point. For example on a clientside password reset page, or in the administrators section of your backend.

Here is the step by step guide to writing a class and interface for handling the logic, along with the controller to communicate with the frontend.

At the time of writing, this has been tested on ASP.NET 5 and Core 2 & 3 using Identity along with Entity Framework 5.

Assumptions

Before following this guide, it's assumed that you are using ASP.NET 5 or Core, with Entity Framework and Identity authentication enabled in your project.

When resetting a password with Identity, you would usually generate a reset token. This reset token can either be forwarded to the client via email or if you are resetting the password via an admin panel, you can immidately use it to reset the password. You should adapt the logic shown below to best fit your requirements.

It's assumed that you have some kind of Users class added to your ConfigureServices method for dependancy injection, for example:

    public void ConfigureServices(IServiceCollection services)
    {            
    services.AddTransient<IUsers, Users>();
    }

Write a Class To Handle The Main Logic

Here is the complete class and interface example:

    public interface IUsers
    {
        public void HardResetPassword(string email, string newPassword);
    }


    public class Users : IUsers
    {
        #region Constructor
        private readonly UserManager<IdentityUser> _userManager;
        public Users(UserManager<IdentityUser> userMgr)
        {
            _userManager = userMgr;
        }
        #endregion

        #region password reset
        public void HardResetPassword(string email, string newPassword)
        {
            var userTask = _userManager.FindByEmailAsync(email);
            userTask.Wait();
            var user = userTask.Result;
            ChangeUserPassword(user, newPassword);
        }

        private string GeneratePasswordResetToken(IdentityUser user)
        {
            var task = _userManager.GeneratePasswordResetTokenAsync(user);
            task.Wait();
            var token = task.Result;
            return token;
        }

        private void ChangeUserPassword(IdentityUser user, string newPassword)
        {
            var token = GeneratePasswordResetToken(user);
            var task = _userManager.ResetPasswordAsync(user, token, newPassword);
            task.Wait();
            var result = task.Result;
        }
        #endregion
    }

To explain what the code does, we use the public method named HardResetPassword to find the user account assigned to the email address you have provided.

We then use the ChangeUserPassword method to call GeneratePasswordResetTokenAsync before using that token to reset the password. If you want to send the user a password reset email, then you can just call GeneratePasswordResetTokenAsync and forward the reset to your email handling code.

Optional: The frontend for Input / Output

Code in the above example can be called from a controller with the following method.

        /// <summary>
        /// Change a user's password
        /// </summary>
        public IActionResult ChangeUserPassword(string email, string password)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                _users.HardResetPassword(email, password);
                return StatusCode(200);
            }
            else
                return StatusCode(500);
        }

End Notes

As you can see, resetting a user password in modern ASP.NET Identity is extremely easy.


Article Categories: # .net # c# # identity # asp.net
Date Created: 11/21/2020
Date Last Updated: 11/22/2020

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Signup To The Newsletter

I try to post a new interesting article every saturday.