我有一个ASP.NET页面,允许管理员更改用户的密码.由于管理员不知道用户的密码,我使用以下内容:
MembershipUser member = Membership.GetUser(_usernameTextBox.Text); member.ChangePassword(member.ResetPassword(), _passNewTextBox.Text);
- 正如这个SO问题所描述的那样.
如果新密码不符合web.config文件中配置的复杂性要求,则密码将被重置,但不会更改为所需的密码.如果新密码不符合复杂性要求,则密码不应发生任何变化.
是否有一种简单的方法可以根据复杂性要求测试新密码?
////// Checks password complexity requirements for the actual membership provider /// /// password to check ///true if the password meets the req. complexity static public bool CheckPasswordComplexity(string password) { return CheckPasswordComplexity(Membership.Provider, password); } ////// Checks password complexity requirements for the given membership provider /// /// membership provider /// password to check ///true if the password meets the req. complexity static public bool CheckPasswordComplexity(MembershipProvider membershipProvider, string password) { if (string.IsNullOrEmpty(password)) return false; if (password.Length < membershipProvider.MinRequiredPasswordLength) return false; int nonAlnumCount = 0; for (int i = 0; i < password.Length; i++) { if (!char.IsLetterOrDigit(password, i)) nonAlnumCount++; } if (nonAlnumCount < membershipProvider.MinRequiredNonAlphanumericCharacters) return false; if (!string.IsNullOrEmpty(membershipProvider.PasswordStrengthRegularExpression) && !Regex.IsMatch(password, membershipProvider.PasswordStrengthRegularExpression)) { return false; } return true; }
您可以使用以下属性来测试密码:
Membership.PasswordStrengthRegularExpression
Membership.MinRequiredPasswordLength
Membership.MinRequiredNonAlphanumericCharacters
请注意,如果尚未在web.config文件中配置,则PasswordStrengthRegularExpression属性将为空字符串.
有关正则表达式匹配的信息,请参阅Regex.IsMatch(String)上的MSDN参考
*感谢Matt的有益评论.