views:

288

answers:

2

Hi all,

I'm looking for a way to create Active Directory users and set their password, preferably without giving my application/service Domain Admin privileges.

I've tried the following:

DirectoryEntry newUser = _directoryEntry.Children.Add("CN=" + fullname, USER);
newUser.Properties["samAccountName"].Value = username;
newUser.Properties["userPassword"].Value = password;
newUser.Properties["mail"].Value = email;
newUser.CommitChanges();

The user is created, but it seems the password is never set on the user.

Does anyone have an idea on how to set the user's password initially when creating the user? I know about

.Invoke("SetPassword", new object[] { password })

But that requires my code to be run with Domain Admin privileges. As I don't really see the point to grant my code Domain Admin privileges, just to set the initial password (I also allow user password resets, but those run in the context of that particular user), I am hoping someone has a clever solution that doesn't require me to do so.

Thanks in advance!

+5  A: 

You can do this whole process much easier now with System.DirectoryServices.AccountManagement (long as you're on .Net 3.5):

See here for a full rundown

Here's a quick example of your specific case:

using(var pc = new PrincipalContext(ContextType.Domain))
{
  using(var up = new UserPrincipal(pc))
  {
    up.SamAccountName = username;
    up.EmailAddress = email;
    up.SetPassword(password);
    up.Enabled = true;
    up.ExpirePasswordNow();
    up.Save();
  }
}
Nick Craver
Don't forget to dispose of the context and principle objects when you're done. This is best done with `using` statements on `pc` and `up`.
tvanfosson
Thanks a lot! That seems to do the trick.
RajenK
@tvanfosson - Great point, even quick examples should be copy/paste worthy, updated!
Nick Craver
+2  A: 

I'd use @Nick's code (wrapped in using statements so the context and principal are disposed properly). As for privileges, you'll need to at least have enough privileges on the OU where you are creating the user to create and manage objects. I'd create a specific user under which your program will run and give it just enough privileges to do the tasks that it needs in that specific OU and no more.

tvanfosson