Search code examples
asp.netasp.net-mvc-4reset-password

Details of ResetPasswordAsync method of UserManager


I want to know how the ResetPasswordAsync() method of .net works from the inside, I tried a lot but unable to find any articles about it, please help.


Solution

  • Below is the code for ResetPasswordAsync()

    public virtual async Task<IdentityResult> ResetPasswordAsync(TUser user, string token, string newPassword)
        {
            ThrowIfDisposed();
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
    
            // Make sure the token is valid and the stamp matches
            if (!await VerifyUserTokenAsync(user, Options.Tokens.PasswordResetTokenProvider, ResetPasswordTokenPurpose, token))
            {
                return IdentityResult.Failed(ErrorDescriber.InvalidToken());
            }
            var result = await UpdatePasswordHash(user, newPassword, validatePassword: true);
            if (!result.Succeeded)
            {
                return result;
            }
            return await UpdateUserAsync(user);
        }
    

    If user has clicked on forgot password then you need to check if user exists then generate a token key for password reset like below

    var callbackUrl = Url.Action("ResetPassword", "Account", 
    new { UserId = user.Id, code = code }, protocol: Request.Url.Scheme);
        await UserManager.SendEmailAsync(user.Id, "Reset Password", 
    "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");    
    

    After that either send recovery mail like shown above or send to your own view for recovery.

    Code is taken from Microsoft GitHub Account