In this article we will discuss two approaches to validate user credentials in Active Directory using C#
- System.DirectoryServices.AccountManagement
- System.DirectoryServices
1. System.DirectoryServices.AccountManagement:
Step 1 – Add reference to System.DirectoryServices.AccountManagement dll into your project.
Step 2 – Add below namespace to your code file
using System.DirectoryServices.AccountManagement;
Step 3 – Use the below code for user creation in AD.
Here we will be creating user in an OU by name “TestOU”.
try { PrincipalContext pricipalContext = null; pricipalContext = new PrincipalContext(ContextType.Domain, "yourdomain.com", "OU=TestOU,DC=yourdomain,DC=com"); //Sometimes we need to connect to AD using service/admin account credentials, in that case the above line of code will be as below //pricipalContext = new PrincipalContext(ContextType.Domain, "yourdomain.com", "OU=TestOU,DC=yourdomain,DC=com","YourAdminUser","YourAdminPassword"); UserPrincipal up = new UserPrincipal(pricipalContext); up.SamAccountName = "TestUser"; up.DisplayName = "Test User"; up.EmailAddress = "test@yourdomain.com"; up.GivenName = "Test"; up.Name = "Test User"; up.Description = "User Created for testing"; up.Enabled = true; up.SetPassword("testPassword"); up.Save(); MessageBox.Show("User Created"); } catch(Exception ex) { }
2. System.DirectoryServices:
Step 1 – Add reference to System.DirectoryServices dll into your project.
Step 2 – Add below namespace to your code file
using System.DirectoryServices;
Step 3 – Use the below code for user creation in AD.
Here we will be creating user in an OU by name “TestOU”.
try { DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://yourdomain.com,OU=TestOU,DC=yourdomain,DC=com"); DirectoryEntry childEntry = directoryEntry.Children.Add("CN=TestUser", "user"); childEntry.Properties["samAccountName"].Value = "TestUser"; childEntry.Properties["mail"].Value = "test@yourdomain.com"; childEntry.CommitChanges(); directoryEntry.CommitChanges(); childEntry.Invoke("SetPassword", new object[] { "testPassword" }); childEntry.CommitChanges(); MessageBox.Show("User Created"); } catch(Exception ex) { }
**Note: If you are receiving an exception “RPC server is unavailable” while creating users in Active Directory, try to open ports 636 and 445. Hopefully this should resolve this issue