Search code examples
asp.netasp.net-mvcasp.net-identity

Asp.net Identity Auto sign out after changing password


After ChangePasswordAsync, the user is signed out automatically and needs to sign in again. How can I keep the user signed in?

private UserManager<ApplicationUser> _userManager
    {
        get
        {
            var userStore = new UserStore<ApplicationUser>(Db);
            return new UserManager<ApplicationUser>(userStore);
        }
    }


public bool ChangePassword(string oldPassword,string password)
    {
        var userId = HttpContext.Current.User.Identity.GetUserId();
        var user = _userManager.ChangePasswordAsync(userId, oldPassword, password);
        if(!user.Result.Succeeded) return false;
        return true;
    }

Solution

  • Instead of calling _userManager.ChangePasswordAsync, modify directly PasswordHash:

    var userName = HttpContext.Current.User.Identity.Name;
    var user = _userManager.Find(userName, oldPassword);
    user.PasswordHash = UserManager.PasswordHasher.HashPassword(password); 
    IdentityResult result = await UserManager.UpdateAsync(user);