How to you test if an ASP.NET membership password will meet configured complexity requirements

asp.netmembershipSecurity

I have a ASP.NET page which allows an administrator to change the password for a user. Since the administrator does not know the user's password, I am using the following:

MembershipUser member = Membership.GetUser(_usernameTextBox.Text);
member.ChangePassword(member.ResetPassword(), _passNewTextBox.Text);

— as described by this SO question.

If the new password does not meet the complexity requirements which are configured in the web.config file, then the password will have been reset, but not changed to the desired one. If the new password does not meet complexity requirements, then the password should not change at all.

Is there an easy way to test the new password against the complexity requirements?

Best Answer

/// <summary>
/// Checks password complexity requirements for the actual membership provider
/// </summary>
/// <param name="password">password to check</param>
/// <returns>true if the password meets the req. complexity</returns>
static public bool CheckPasswordComplexity(string password)
{
    return CheckPasswordComplexity(Membership.Provider, password);
}


/// <summary>
/// Checks password complexity requirements for the given membership provider
/// </summary>
/// <param name="membershipProvider">membership provider</param>
/// <param name="password">password to check</param>
/// <returns>true if the password meets the req. complexity</returns>
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;
}