Using Active Directory in a C# .NET Web Application

modified

Active Directory is the primary user management system used by business and enterprise networks. It’s basically just another kind of database, similar to MSSQL or Oracle, but with its own type of query language and protocol, which is based on LDAP.

Active Directory in C# ASP .NET Web Application

Being able to query objects in Active Directory from within a C# ASP .NET web application can be a great knowledge tool. Many businesses who are moving their desktop applications to the web are asking for their .NET web applications to contain forms-based LDAP authentication and other hooks into Active Directory to process user objects.

The DirectoryEntry Object

The fundamental starting point for a .NET application using Active Directory is to include the System.DirectoryServices library. This contains the basic Active Directory library routines used to query. Communicating with Active Directory starts out with obtaining a DirectoryEntry object. This object is your root connection into the LDAP database, from which you can query for additional folders or objects. In order to obtain the DirectoryEntry object, you will need an Active Directory server address, username, and password. The server address can be an IP address or a complete LDAP path in the form LDAP://MyCompany.com/DC=MyCompany,DC=com

Connecting to Active Directory for the DirectoryEntry Object

Below is an example function to obtain a DirectoryEntry object for a fictional Active Directory server. Note the user of AuthenticationTypes.Secure to indicate we are making a secure authenticated connection to Active Directory. If you specify a regular user login, you will be restricted in what you may access. This can be handy to enforce role policies within your .NET web application. Alternatively, by connecting with an administrative account, you can perform administrative Active Directory functions such as modifying users, creating users, deleting users, etc.

1
2
3
4
5
6
7
8
using System.DirectoryServices;
private DirectoryEntry GetDirectoryObject()
{
    DirectoryEntry oDE;
    oDE = new DirectoryEntry("LDAP://192.168.1.101", "administrator", "password", AuthenticationTypes.Secure);
    return oDE;
}

Grabbing a User from Active Directory in C# ASP .NET

Querying a User in Active Directory in C# ASP .NET Web Application

After connecting to Active Directory, you will want to query for an object, such as a user. The below code sample shows how to get a user from Active Directory based on their login name. Note that we use a specific Active Directory query language where clauses are included inside parenthesis. You can only query on certain fields. The below example uses the field “SAMAccountName”, which is another word for “username” or “login” in Active Directory. Notice we also query for an objectClass of type “user”. Another objectClass is of type “contact”. After finding the DirectoryEntry, we create a new DirectoryEntry object pointing to the result and use our administrative login information in the connection (so that we can perform admin functions on the object).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private DirectoryEntry GetUser(string UserName)
{
    DirectoryEntry de = GetDirectoryObject();
    DirectorySearcher deSearch = new DirectorySearcher();
    deSearch.SearchRoot = de;
    deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + UserName + "))";
    deSearch.SearchScope = SearchScope.Subtree;
    SearchResult results = deSearch.FindOne();
    if (!(results == null))
    {
       de = new DirectoryEntry(results.Path, "administrator", "password", AuthenticationTypes.Secure);
       return de;
    }
    else
    {
       return null;
    }
}

Modifying a User’s Properties in Active Directory in C# .NET

Modifying the property of an Active Directory object in C# .NET is fairly simple. You access the DirectoryEntry’s Properties field, modify the values as needed (be sure to check for null), and finally call CommitChanges to commit and save the changes. An example is shown below, which modifies the user’s Display Name property (this is the name shown as their real name in Active Directory or the Global Address List).

1
2
3
4
5
6
7
8
9
  DirectoryEntry de = GetUser("john.doe");
  if (de != null)
  {
  if (de.Properties["displayName"] != null && de.Properties["displayName"].Value != null)
  {
      de.Properties["displayName"].Value = "John, Doe (Nice Guy)";
      de.CommitChanges();
  }
}

Note in the above code, if you do not call de.CommitChanges(), the changes will not be saved to Active Directory. Another important note is that any changes you make will not be instantly visible in applications that query Active Directory (such as Active Directory Users and Computers in the control panel). This is because the changes need to synchronize over the servers and throughout the network. Some networks may take between 5-30 minutes for changes to be visible.

Querying Multiple Users in Active Directory with C# ASP .NET

The above discussed querying for individual DirectoryEntry objects. However, if you wish to retrieve a list of objects, you will need to use the SearchResultCollection type combined with deSearch.FindAll instead of deSearch.FindOne.

1
2
3
4
5
6
7
8
SearchResultCollection MyUsers = GetAllUsers();
if (MyUsers != null && MyUsers.Count > 0)
{
   foreach (SearchResult m_User in MyUsers)
   {
     DirectoryEntry de = m_User.GetDirectoryEntry();
   }
}

Using Active Directory within a C# .NET Web Application can be a powerful tool for business and enterprise networks. By designing web applications to suit the enterprise world, more desktop applications can be ported to the web and empower organizations.

Feel free to contact Primary Objects if you are in need of a C# .NET Web Application dealing with Active Directory functionality.

About the Author

This article was written by Kory Becker, software developer and architect, skilled in a range of technologies, including web application development, machine learning, artificial intelligence, and data science.

Share