简体   繁体   中英

Generate Random Password which meets Active Directory Password Policy Complexity Requirements Programmatically

I am trying to setpassword with for forget password functionality.

public string SetPassWord(string userName, string randomPassword)
{
    string result = string.Empty;
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName);
    AdUser adUser = new AdUser();
    if (user != null)
    {
        user.SetPassword(randomPassword);
        result = "Success";
    }
    return result;
}

I need to generate the random password which meets the following complexity:

  • Not contain the user's account name or parts of the user's full name that exceed two consecutive characters
  • Be at least six characters in length
  • Contain characters from three of the following four categories:
    • English uppercase characters (A through Z)
    • English lowercase characters (a through z)
    • Base 10 digits (0 through 9)
    • Non-alphabetic characters (for example, !, $, #, %)

Complexity requirements are enforced when passwords are changed or created.

Is there any inbuilt method which serves the above requirements? I have used below method to generate password randomely:

string randomPassword = Membership.GeneratePassword(8, 0).Replace('<','!').Replace('>', '#');

It throws the error when I am trying to set password. Appreciate if there is and validation or inbuilt method to achieve the above requirement.

I think using ActiveDirectoryMembershipProvider's ResetPassword() method should do exactly what you're looking for. MSDN - ActiveDirectoryMembershipProvider - ResetPassword()

See if something like this works for you. I originally wrote this for .Net Identity 2 but it should point you in the right direction. You can see how I'm using it on GitHub

var validator = new PasswordValidator
{
    RequiredLength = 6,
    RequireNonLetterOrDigit = false,
    RequireDigit = true,
    RequireLowercase = true,
    RequireUppercase = true
};

passwords.Add(GeneratePassword(validator));


private static string GeneratePassword(PasswordValidator passwordValidator)
{
    var rnd = new Random();

    while (true)
    {
        var password = Membership.GeneratePassword(passwordValidator.RequiredLength, 0);
        if ((passwordValidator.RequireDigit && !password.Any(char.IsDigit)) || (passwordValidator.RequireLowercase && !password.Any(char.IsLower)) || (passwordValidator.RequireUppercase && !password.Any(char.IsUpper)))
            continue;

        if (!passwordValidator.RequireNonLetterOrDigit) password = Regex.Replace(password, @"[^a-zA-Z0-9]", m => rnd.Next(0, 10).ToString());
        return password;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM