ASP.NET Identity change password

前端 未结 10 1867
礼貌的吻别
礼貌的吻别 2020-11-29 18:09

I need ability to change password for user by admin. So, admin should not enter a current password of user, he should have ability to set a new password. I look at ChangePas

相关标签:
10条回答
  • 2020-11-29 18:46

    Yes, you are correct. ResetPassword through token is a preferred approach. Sometime back, I created a complete wrapper over .NET Identity and code can be found here. It might be helpful for you. You can also find nuget here. I also explained the library in a blog here. This wrapper is easily consumable as nuget and create all required configs during installation.

    0 讨论(0)
  • 2020-11-29 18:48

    This is just a refinement on the answer provided by @Tseng. (I had to tweak it to get it to work).

    public class AppUserManager : UserManager<AppUser, int>
    {
        .
        // standard methods...
        .
    
        public async Task<IdentityResult> ChangePasswordAsync(AppUser user, string newPassword)
        {
            if (user == null)
                throw new ArgumentNullException(nameof(user));
    
            var store = this.Store as IUserPasswordStore<AppUser, int>;
            if (store == null)
            {
                var errors = new string[] { "Current UserStore doesn't implement IUserPasswordStore" };
                return IdentityResult.Failed(errors);
            }
    
            var newPasswordHash = this.PasswordHasher.HashPassword(newPassword);
            await store.SetPasswordHashAsync(user, newPasswordHash);
            await store.UpdateAsync(user);
            return IdentityResult.Success;
        }
    }
    

    Note: this applies specifically to a modified setup that uses int as the primary keys for users and roles. I believe it would simply be a matter of removing the <AppUser, int> type args to get it to work with the default ASP.NET Identity setup.

    0 讨论(0)
  • 2020-11-29 18:49

    In .net core 3.0

    var token = await UserManager.GeneratePasswordResetTokenAsync(user);
    var result = await UserManager.ResetPasswordAsync(user, token, password);
    
    0 讨论(0)
  • 2020-11-29 18:50

    If you don't have user's current password and still want to change the password. What you could do instead remove user's password first and then add the new password. This way you will be able to change user's password without needing current password of that user.

    await UserManager.RemovePasswordAsync(user);
    await UserManager.AddPasswordAsync(user, model.Password);
    
    0 讨论(0)
提交回复
热议问题