Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Change password in asp.net core

Suggested Videos
Part 118 - ASP.NET Core password reset token lifetime | Text | Slides
Part 119 - ASP.NET Core custom token provider | Text | Slides
Part 120 - ASP.NET Core encryption and decryption example | Text | Slides

In this video we will discuss how to implement change password view in asp.net core MVC.

Change password view example

A logged in user can change his password using the following change password view.

asp.net core change password example


Why current password is required

This is to make sure it is the actual account owner who is changing the password. Though you are already logged-in, asking for the current password prevents a malicious from changing another user password if that user has briefly walked away from the computer or forgot to logout from a public computer.


UserManager ChangePasswordAsync Method

var result = await userManager.ChangePasswordAsync(user, 
    model.CurrentPassword, model.NewPassword);

It is the ChangePasswordAsync() method of the UserManager service that we use to change a logged-in user password. This method takes 3 parameters.
  1. The logged-in user whose password is being changed
  2. Current password
  3. New password
SignInManager RefreshSignInAsync() Method

await signInManager.RefreshSignInAsync(user);

Call SignInManager service RefreshSignInAsync() method, after the password is successfully changed. As the name implies, this method refreshes the logged-in user sign-in cookie.

Change Password ViewModel

public class ChangePasswordViewModel
{
    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Current password")]
    public string CurrentPassword { get; set; }

    [Required]
    [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; }
}

Change Password View

@model ChangePasswordViewModel

<h2>Change Password</h2>
<hr />
<div class="row">
    <div class="col-md-12">
        <form method="post">
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="CurrentPassword"></label>
                <input asp-for="CurrentPassword" class="form-control" />
                <span asp-validation-for="CurrentPassword" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="NewPassword"></label>
                <input asp-for="NewPassword" class="form-control" />
                <span asp-validation-for="NewPassword" 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-primary">Update</button>
        </form>
    </div>
</div>

Change Password Confirmation View

<h4>
    Your password is successfully changed.
</h4>

HttpGet ChangePassword Action

[HttpGet]
public IActionResult ChangePassword()
{
    return View();
}

HttpPost ChangePassword Action

[HttpPost]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return RedirectToAction("Login");
        }

        // ChangePasswordAsync changes the user password
        var result = await userManager.ChangePasswordAsync(user,
            model.CurrentPassword, model.NewPassword);

        // The new password did not meet the complexity rules or
        // the current password is incorrect. Add these errors to
        // the ModelState and rerender ChangePassword view
        if (!result.Succeeded)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
            return View();
        }

        // Upon successfully changing the password refresh sign-in cookie
        await signInManager.RefreshSignInAsync(user);
        return View("ChangePasswordConfirmation");
    }

    return View(model);
}

Change password menu item in Layout view

<li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink"
        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Manage
    </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
        <a class="dropdown-item" asp-controller="Administration" asp-action="ListUsers">
            Users
        </a>
        <a class="dropdown-item" asp-controller="Administration" asp-action="ListRoles">
            Roles
        </a>
        <a class="dropdown-item" asp-controller="Account"
            asp-action="ChangePassword">
            Password
        </a>
    </div>
</li>

asp.net core tutorial for beginners

No comments:

Post a Comment

It would be great if you can help share these free resources