Link to home
Start Free TrialLog in
Avatar of mrichmon
mrichmon

asked on

Active directory programming - setting user password

I have the following code :

(C# code)

DirectoryEntry de = new DirectoryEntry();

// Set credentials of an AD account that is priveledged to be able to create users
de.Username = username;
de.Password = password;

// Set active LDAP path
de.Path = LDAPpath;

// Assign the users in the LDAPpath to a variable so we can manipulate it (add users)
DirectoryEntries users = de.Children;

// Add user account
DirectoryEntry user = users.Add("CN=" + LastName + "\\, " + FirstName, "user");

// Set additional properties of new account
user.Properties["samAccountName"].Add(username); // Login name
user.Properties["givenName"].Add(FirstName); // First Name
user.Properties["sn"].Add(LastName); // Last Name
user.Properties["userPassword"].Add(password);

// Commit changes so far so we can then add additonal account properties
user.CommitChanges();

// Set the account to be a "normal account" (0x10000)
user.Properties["userAccountControl"].Value = ((int) user.Properties["userAccountControl"].Value) | 0x10000;

// Set the "account disable" to false (account disable = 0x2)
user.Properties["userAccountControl"].Value = ((int) user.Properties["userAccountControl"].Value) & ~0x2;

// Set profile path
user.Properties["profilePath"].Add(ProfilePath);

// Commit final changes
user.CommitChanges();


However, I have found out that it doesn't work.

The account is created, but I cannot log in using the password that was set in this line :
user.Properties["userPassword"].Add(password);


This code is basically adapted from the WROX Professional C# 2nd edition book and they use that method to set the password.

I even tried hardcoding in a string - no luck.

Any ideas on how to create a password for a new account created in programatically?

PS If I go onto the Domain controller and reset the password for the account then it works so I know that other than the password the account is getting correctly created.

Thanks.
Avatar of eternal_21
eternal_21

Instead of:

  user.Properties["userPassword"].Add(password);

Try this:

  user.Invoke("SetPassword", new object[] {password});
ASKER CERTIFIED SOLUTION
Avatar of mrichmon
mrichmon

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Did you try using user.Invoke("SetPassword", new object[] {password}) *before* doing your commit?
Avatar of mrichmon

ASKER

yes.

didn't  work.

In both cases the commitchanges needed to happen BEFORE any password commands could be issued.  I actually found documentation from Microsoft verifying this.

It was not true on Win NT 4, but is true of the newer AD domains according to the article....