Permissions required for adding an Active Directory account through code
I'm attempting to write a program that would automatically create active directory accounts using data from an external data source. The problem that I am running into is that I am always getting an UnAuthorizedAccessException but I for the life of me can't think of what permissions to apply. I've even gone all the way to the root object and given my own account full control which doesn't seem to make any differen开发者_开发技巧ce. I know that I can access the server since the organizationUnit and de objects are populated correctly.
DirectoryEntry de = new DirectoryEntry("LDAP://MYLOCALADDRESS");
de.Password = "thePassword";
de.Username = "theUserName";
de.AuthenticationType = AuthenticationTypes.Secure ;
DirectoryEntry organizationalUnit = de.Parent;
DirectoryEntry newUser = organizationalUnit.Children.Add("TESTADD ", de.SchemaClassName);
//Exception happens on this line
newUser.CommitChanges();
Any help would be appreciated!
At a glance I'd say your "TESTADD " needs to start with "CN="
For active directory I get all my samples from this codeproject:
public string CreateUserAccount(string ldapPath, string userName,
string userPassword)
{
try
{
string oGUID = string.Empty;
string connectionPrefix = "LDAP://" + ldapPath;
DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
DirectoryEntry newUser = dirEntry.Children.Add
("CN=" + userName, "user");
newUser.Properties["samAccountName"].Value = userName;
newUser.CommitChanges();
oGUID = newUser.Guid.ToString();
newUser.Invoke("SetPassword", new object[] { userPassword });
newUser.CommitChanges();
dirEntry.Close();
newUser.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//DoSomethingwith --> E.Message.ToString();
}
return oGUID;
}
精彩评论