In this article, we will focus on the comprehensive creation of user accounts in Active Directory using C#. This includes ensuring proper security configurations, forcing users to change their passwords upon first login, setting account expiration, and assigning managers to the newly created user accounts.
By automating these tasks in C#, you not only ensure consistency but also improve administrative efficiency and reduce human error. We’ll walk through the entire process step by step, explaining each part of the code along the way.
Why Automate User Account Creation in Active Directory?
Managing users in Active Directory through manual intervention is time-consuming and error-prone, especially when dealing with large organizations. Automating the creation process with C# allows you to:
- Enforce Security Standards: Automatically configure secure defaults such as requiring a password change on first login.
- Streamline Organizational Structure: Programmatically assign managers to users.
- Improve Consistency: Ensure that all user accounts adhere to predefined policies and standards.
Setting Up a User Account with Security and Manager Assignment
The following steps explain how to create a new user account, enforce security settings like password changes, set an account expiration date, and assign a manager from Active Directory.
Code Walkthrough: Creating a User with Security and Manager Setup
using System;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;
class Program
{
static void Main(string[] args)
{
// Directory context for the domain controller
string domainPath = "LDAP://YourDomainController";
string username = "secureuser"; // New user's username
string managerSamAccountName = "manageruser"; // Manager's SamAccountName
string password = "ComplexP@ss123"; // Password for the new user
string displayName = "Secure User"; // Display name for the user
DateTime accountExpirationDate = new DateTime(2025, 12, 31); // Expiration date of the account
// Create a variable for UserPrincipalName and EmailAddress
string upnAndEmail = $"{username}@yourdomain.com"; // User Principal Name and Email Address
using (var context = new PrincipalContext(ContextType.Domain, domainPath))
{
// Step 1: Find the manager by SamAccountName
UserPrincipal manager = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, managerSamAccountName);
if (manager == null)
{
Console.WriteLine($"Manager with SamAccountName '{managerSamAccountName}' not found.");
return;
}
// Step 2: Create the user with security settings and manager assignment
UserPrincipal user = new UserPrincipal(context)
{
SamAccountName = username,
Name = displayName,
UserPrincipalName = upnAndEmail, // Set UPN from variable
EmailAddress = upnAndEmail, // Set email from variable
DisplayName = displayName,
Enabled = true // Enable the account immediately
};
// Step 3: Set password and security settings
user.SetPassword(password); // Set the user's password
user.PasswordNeverExpires = false; // Password will expire
user.UserCannotChangePassword = false; // Allow the user to change their password
// Force the user to change their password at next login
user.ExpirePasswordNow();
// Step 4: Set account expiration date
user.AccountExpirationDate = accountExpirationDate;
// Step 5: Assign the manager to the user
user.Manager = manager.DistinguishedName;
// Save the user to Active Directory
user.Save();
Console.WriteLine("Secure user account created with manager assigned.");
// Step 6: Print user details for validation
PrintUserDetails(user);
}
}
// Function to validate and print user information
static void PrintUserDetails(UserPrincipal user)
{
DirectoryEntry de = (DirectoryEntry)user.GetUnderlyingObject();
// Retrieving user details
string displayName = user.DisplayName;
string userPrincipalName = user.UserPrincipalName;
string email = user.EmailAddress;
string description = de.Properties["description"].Value != null ? de.Properties["description"].Value.ToString() : "No description";
string samAccountName = user.SamAccountName;
DateTime? passwordLastSet = user.LastPasswordSet;
DateTime? passwordExpiration = user.AccountExpirationDate;
bool passwordCannotBeChanged = user.UserCannotChangePassword;
// Printing out the user information
Console.WriteLine($"User Principal Name: {userPrincipalName}");
Console.WriteLine($"Email: {email}");
Console.WriteLine($"Display Name: {displayName}");
Console.WriteLine($"Description: {description}");
Console.WriteLine($"SAM Account Name: {samAccountName}");
Console.WriteLine($"Password Last Changed: {passwordLastSet}");
Console.WriteLine($"Password Expiration Date: {passwordExpiration ?? DateTime.MaxValue}");
Console.WriteLine($"Password Cannot Be Changed by User: {passwordCannotBeChanged}");
Console.WriteLine($"Manager: {user.Manager}");
}
}
Breaking Down the Code
Let’s go over each important part of the code to explain what is happening and why.
Step 1: Finding the Manager by SamAccountName
We use UserPrincipal.FindByIdentity()
to search for the manager’s account using their SamAccountName
. This method returns a UserPrincipal
object representing the manager in Active Directory.
UserPrincipal manager = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, managerSamAccountName);
if (manager == null)
{
Console.WriteLine($"Manager with SamAccountName '{managerSamAccountName}' not found.");
return;
}
This step ensures that we retrieve the correct manager from Active Directory. If the manager cannot be found, the process stops with a message.
Step 2: Creating the User Account
We then create a new user in Active Directory by instantiating the UserPrincipal
class and setting various properties:
SamAccountName
: The account name.UserPrincipalName
: A unique identifier for the user in Active Directory.EmailAddress
: Set to the same value asUserPrincipalName
for consistency.DisplayName
: The user's full display name, typically shown in address books and other organizational systems.
UserPrincipal user = new UserPrincipal(context)
{
SamAccountName = username,
Name = displayName,
UserPrincipalName = upnAndEmail, // Set UPN from variable
EmailAddress = upnAndEmail, // Set email from variable
DisplayName = displayName,
Enabled = true // Enable the account immediately
};
Step 3: Setting Security Attributes
We enforce several security-related properties when creating the account:
SetPassword()
: Defines the user’s initial password.PasswordNeverExpires
: Set tofalse
to ensure that the user’s password will eventually expire.UserCannotChangePassword
: Set tofalse
to allow the user to change their password after logging in.ExpirePasswordNow()
: Forces the user to change their password upon first login.
user.SetPassword(password); // Set the user's password
user.PasswordNeverExpires = false; // Password will expire
user.UserCannotChangePassword = false; // Allow the user to change their password
user.ExpirePasswordNow(); // Force password change at next login
Step 4: Setting Account Expiration
We can also set an expiration date for the user account. If the date is reached, the account will be automatically disabled.
user.AccountExpirationDate = accountExpirationDate;
Step 5: Assigning the Manager
Using the manager’s DistinguishedName
(retrieved earlier), we assign the manager to the new user by setting the Manager
property.
user.Manager = manager.DistinguishedName;
Step 6: Saving the User and Validating
After configuring the user account, we save it to Active Directory using the user.Save()
method. Then, we call the PrintUserDetails()
function to validate that all user properties have been set correctly.
user.Save();
Console.WriteLine("Secure user account created with manager assigned.");
PrintUserDetails(user);
Conclusion
This article has walked through the process of creating a secure user account in Active Directory, including setting security properties and assigning a manager. By automating these tasks with C#, you ensure consistency across your organization and save valuable administrative time.