A Web Application is creating a user from a Personnel Management Page which in turn adds the user to the Active Directory. Here is code to do this:
DirectoryEntry Folder = new DirectoryEntry("LDAP://XXXX.com/CN=ContainerName, DC=XXXX, DC=com", admin, adminPwd, AuthenticationTypes.None);
if (Folder.SchemaEntry.Name == "container")
{
DirectoryEntry user = Folder.Children.Add("CN=" + txtFirstname.Text + " " + txtLastname.Text, "User");
if (DirectoryEntry.Exists(user.Path))
{
// Error Msg Here
}
else
{
// Required attributes
if (txtFirstname.Text != "" && txtLastname.Text != "") { user.Properties["sAMAccountName"].Value = txtFirstname.Text.ToLower() + "." + txtLastname.Text.ToLower(); }
if (txtFirstname.Text + " " + txtLastname.Text != "") { user.Properties["cn"].Value = txtFirstname.Text + " " + txtLastname.Text; }
// More controls to populate Optional AD attributes. Not entered to conserve space. The code works however.
user.CommitChanges();
int val = (int)user.Properties["userAccountControl"].Value;
user.Properties["userAccountControl"].Value = val & ~0x2;
user.Properties["pwdLastSet"].Value = 0;
user.CommitChanges();
user.Invoke("SetPassword", new object[] { "SuperSecretPassword" });
user.CommitChanges();
}
The issue is that after the account has been created, the invoke method fails to set the password. Every attempt to set the password returns this error in the catch statement:
System.Reflection.TargetInvocationException was caught
HResult=-2146232828
Message=Exception has been thrown by the target of an invocation.
Source=System.DirectoryServices
StackTrace:
at System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)
at Personnel_Govt.CreateUser() in c:\inetpub\wwwroot\TestingFolder\Personnel\Add\Govt.aspx.cs:line 148
at Personnel_Govt.btnSubmit_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot\TestingFolder\Personnel\Add\Govt.aspx.cs:line 95
InnerException: System.UnauthorizedAccessException
HResult=-2147024891
Message=One or more input parameters are invalid
Source=Active Directory
InnerException:
If the password is set manually in AD with 'Reset Required' checked after the account is created, it will work.
Why is the method for setting the password failing???
The problem is solved. Apparently the account for Internet Information Services (IIS_IUSRS) did not have permissions to SET Passwords for Active directory. It could CHANGE passwords but not SET them.
To allow an ASP.NET page to SET an AD Password on account creation, I had to run "Active Directory Users and Computers", right-click the domain, select "Delegate Control". This opens a wizard which will allow you to grant the account IIS_IUSRS permissions to make changes to AD.