asp.net membership change password without knowing old one

后端 未结 10 1974
日久生厌
日久生厌 2020-12-24 04:48

Evaluting the method signature, it is required to know old password while changing it.

membershipUser.ChangePassword(userWrapper.OldPassword, userWrapper.Pas         


        
相关标签:
10条回答
  • 2020-12-24 05:31

    The other answers here are correct, but can leave the password in an unknown state.

    ChangePassword will throw exceptions if the password doesn't meet the requirements laid out in Web.Config (minimum length, etc.). But it only fails after ResetPassword has been called, so the password will not be known to the original user or to the person who's tried to change it. Check for complexity requirements before changing the password to avoid this:

    var user = Membership.GetUser(userName, false);
    
    if ((newPassword.Length >= Membership.MinRequiredPasswordLength) &&
        (newPassword.ToCharArray().Count(c => !Char.IsLetterOrDigit(c)) >=
             Membership.MinRequiredNonAlphanumericCharacters) &&
        ((Membership.PasswordStrengthRegularExpression.Length == 0) ||
             Regex.IsMatch(newPassword, Membership.PasswordStrengthRegularExpression))) {
    
        user.ChangePassword(user.ResetPassword(), newPassword);
    } else {
        // Tell user new password isn't strong enough
    }
    
    0 讨论(0)
  • 2020-12-24 05:32

    @Rob Church is right:

    The other answers here are correct but can leave the password in an unknown state.

    However, instead of his solution to do the validation by hand, I would try to change the password using the ResetPassword from token method and catch and show the error:

    var user = UserManager.FindByName(User.Identity.Name);
    string token = UserManager.GeneratePasswordResetToken(user.Id);
    var result = UserManager.ResetPassword(user.Id, token, model.Password);
    if (!result.Succeeded){
        // show error
    }
    
    0 讨论(0)
  • 2020-12-24 05:34
     string username = "UserName";
     string userpassword = "NewPassword";   
     MembershipUser mu = Membership.GetUser(username, false);
     mu.ChangePassword(mu.ResetPassword(username), userpassword);
    
    0 讨论(0)
  • 2020-12-24 05:36

    This code mentioned on posts above is working:

    string username = "username";
    string password = "newpassword";
    MembershipUser mu = Membership.GetUser(username);
    mu.ChangePassword(mu.ResetPassword(), password);
    

    But you have to set requiresQuestionAndAnswer="false" in web.config in membership provider tag. If it is true, resetpassword method generate an error "Value can not be null". In this case you must supply question answer as parameter to ResetPassword.

    0 讨论(0)
提交回复
热议问题