Introduction:

In this article we are going to explain how to use forgot password and reset password in mvc core or how to use ASP.NET Core Identity to forgot password and reset password in MVC Application with example.

Description:

ASP.NET Mvc Core Identity allows us to forgot password and reset password functionality to our system. Sometimes user’s forgot their password for this need Add an Action link on login page if the user forgot password.The link redirects the user to the below page from where the user can get a reset link on the registered email id.

Note: The user should be already-registered a user.

Let’s see how to create a simple forgot password Functionality in ASP.NET Mvc Core.

This is how the forgot password page looks .The user needs to enter the registered and valid email id on which the reset link will be sent.

 Forgot Password And Reset Password Link On Email In Asp.Net MVC Core



ForgotPassword.cshtml


@model ForgotPasswordViewModel
@{
    ViewData["Title"] = "Forgot your password?";
}
 
<h2>@ViewData["Title"]</h2>
<h4>Enter your email.</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="ForgotPassword" method="post">
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Email"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
    </div>
</div>
 
@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
}

 

Below is the code of the forgot password action method:

 

      [HttpGet]
        [AllowAnonymous]
        public IActionResult ForgotPassword()
        {
            return View();
        }
 
        [HttpPost]
        [AllowAnonymous]
       [ValidateAntiForgeryToken]
        public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);
                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return RedirectToAction(nameof(ForgotPasswordConfirmation));
                }
 
                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);
                var callbackUrl =Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
                await _emailSender.SendEmailAsync(model.Email, "Reset Password",
                   $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
                return RedirectToAction(nameof(ForgotPasswordConfirmation));
            }
 
            // If we got this far, something failed, redisplay form
            return View(model);
        }

 

 

Now click on Submit Button, It will send a reset link on the registered email.Once the mail is received the user needs to click on the reset link which will redirect the user to the reset password page.

The mail will look like the below  details,

Your changed password

Please find the Password Reset Link.

http://www.example.com/Account/ResetPassword?email=**************.com&code=UNbRRYVXWO4mqC15Gfdpaw2

On clicking the above link you will be redirected to a reset password page with the return/ reset token.The return/reset token is attached with the url of the reset password page and hepls in replacing the old password with the new one.User needs to enter the new password in the below page to reset it.

Forgot Password And Reset Password Link On Email In Asp.Net MVC Core


ResetPassword.cshtml

 

@model ResetPasswordViewModel
@{
    ViewData["Title"]= "Reset password";
}
 
<h2>@ViewData["Title"]</h2>
<h4>Reset your password.</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="All" class="text-danger"></div>
            <input asp-for="Code" type="hidden" />
            <div class="form-group">
                <label asp-for="Email"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password"></label>
                <input asp-for="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ConfirmPassword"></label>
                <input asp-for="ConfirmPassword" class="form-control" />
                <span asp-validation-for="ConfirmPassword" class="text-danger"></span>
            </div>
            <button type="submit" class="btn btn-default">Reset</button>
        </form>
    </div>
</div>
 
@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
}

 

The code for Resetting password is as below:

     [HttpGet]
        [AllowAnonymous]
        public IActionResult ResetPassword(string code = null)
        {
            if (code == null)
            {
                throw new ApplicationException("A code must be supplied for password reset.");
            }
            var model = new ResetPasswordViewModel { Code = code };
            return View(model);
        }
 
        [HttpPost]
        [AllowAnonymous]
       [ValidateAntiForgeryToken]
        public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user == null)
            {
                // Don't reveal that the user does not exist
                return RedirectToAction(nameof(ResetPasswordConfirmation));
            }
            var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
            if (result.Succeeded)
            {
                return RedirectToAction(nameof(ResetPasswordConfirmation));
            }
           AddErrors(result);
            return View();
        }

The Return token in Identity in Mvc hepls in replacing the old password with the new one.The ResetPassword() method in Identity is used to reset the password with the help of return token of the registered user.

 

I hope it will help to you after reading it.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like