IC Improve Code Recipes

Recipe 7.5 · C#

Active Directory Lookups with System.DirectoryServices.AccountManagement

Problem

Intranet applications need to look up a user's display name and e-mail, check group membership for authorization, and occasionally validate a user name and password. Legacy code builds LDAP filter strings by hand with DirectorySearcher, never disposes the results, misses nested groups, and leaks connections until the domain controller starts refusing them.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: hand-built filter (injectable), nothing disposed.
DirectoryEntry root = new DirectoryEntry("LDAP://DC=corp,DC=local");
DirectorySearcher searcher = new DirectorySearcher(root);
searcher.Filter = "(&(objectClass=user)(sAMAccountName=" +
    userName + "))";
SearchResult result = searcher.FindOne();
string email = result.Properties["mail"][0].ToString();

The improved recipe

Use System.DirectoryServices.AccountManagement (NuGet package of the same name on modern .NET), which builds queries for you, and dispose every context and principal. This API is Windows-only; the attribute makes the compiler warn if you call it from cross-platform code.

C#
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Runtime.Versioning;

namespace ImproveCode.Security;

public sealed record DirectoryUser(
    string SamAccountName,
    string? DisplayName,
    string? Email,
    bool IsEnabled);

[SupportedOSPlatform("windows")]
public sealed class DirectoryLookup(
    string domain, string? container = null)
{
    public DirectoryUser? FindUser(string samAccountName)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(samAccountName);

        using var context = CreateContext();
        using UserPrincipal? user = UserPrincipal.FindByIdentity(
            context, IdentityType.SamAccountName, samAccountName);

        return user is null
            ? null
            : new DirectoryUser(
                user.SamAccountName,
                user.DisplayName,
                user.EmailAddress,
                user.Enabled ?? false);
    }

    /// <summary>Security groups, including nested membership.
    /// </summary>
    public IReadOnlyList<string> GetSecurityGroups(
        string samAccountName)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(samAccountName);

        using var context = CreateContext();
        using UserPrincipal? user = UserPrincipal.FindByIdentity(
            context, IdentityType.SamAccountName, samAccountName);
        if (user is null)
        {
            return Array.Empty<string>();
        }

        var names = new List<string>();
        using PrincipalSearchResult<Principal> groups =
            user.GetAuthorizationGroups();

        foreach (Principal group in groups)
        {
            using (group)
            {
                if (group.Name is not null)
                {
                    names.Add(group.Name);
                }
            }
        }

        return names;
    }

    public bool ValidateCredentials(string userName, string password)
    {
        if (string.IsNullOrWhiteSpace(userName)
            || string.IsNullOrEmpty(password))
        {
            return false; // an empty password can bind anonymously
        }

        using var context = CreateContext();
        return context.ValidateCredentials(
            userName,
            password,
            ContextOptions.Negotiate
            | ContextOptions.Signing
            | ContextOptions.Sealing);
    }

    private PrincipalContext CreateContext() =>
        new(ContextType.Domain, domain, container);
}

Usage:

C#
if (OperatingSystem.IsWindows())
{
    var directory = new DirectoryLookup("corp.example.com");
    DirectoryUser? user = directory.FindUser("jdoe");
    IReadOnlyList<string> groups = directory.GetSecurityGroups("jdoe");
}

How it works

PrincipalContext represents a connection to the domain. FindByIdentity builds and escapes the LDAP query itself, so a user name containing * or ) can't change the filter the way string concatenation can. UserPrincipal exposes the common attributes as typed properties (DisplayName, EmailAddress, Enabled) instead of Properties["mail"][0].

Both the context and every principal hold unmanaged directory resources. The using declarations release them when the method ends, including each Principal returned while iterating the group results. Undisposed directory objects are the most common cause of the slow memory growth and "server is not operational" errors I see in intranet apps that have run for months.

GetAuthorizationGroups returns security groups including nested membership, computed from the user's token groups. That matches how Windows itself makes access decisions. IsMemberOf and GetGroups look only at direct membership, so a user in "Finance Managers," which is itself in "Finance," appears not to be in "Finance."

ValidateCredentials with Negotiate, Signing and Sealing uses Kerberos or NTLM over a protected channel rather than a plain LDAP simple bind, which would send the password in clear text without LDAPS. The empty-password guard matters: some directory configurations treat a bind with an empty password as an anonymous bind and report success.

[SupportedOSPlatform("windows")] tells the platform compatibility analyzer that callers must be on Windows. Code that might run on Linux gets a build warning unless it checks OperatingSystem.IsWindows() first, as in the usage snippet.

Variations and pitfalls

  • For authentication in ASP.NET Core, prefer Windows Authentication (IIS) or the Negotiate handler (Microsoft.AspNetCore.Authentication.Negotiate) and check groups with User.IsInRole(...). Users never type their password into your app. Use this recipe for lookups and admin screens.
  • Directory calls take tens to hundreds of milliseconds. Cache display names and group lists for a few minutes (Chapter 3) instead of querying on every request.
  • GetAuthorizationGroups can throw PrincipalOperationException when a group SID from a trusted domain can't be resolved. Catch that specific exception and decide whether to deny or fall back.
  • For searches by name, use PrincipalSearcher with a UserPrincipal as a query-by-example filter, and set a size limit; an unbounded search on a large directory is slow for everyone.
  • Azure AD (Entra ID) isn't LDAP. Cloud-only users need Microsoft Graph instead of this API.

On .NET Framework

On .NET Framework the same API ships in the framework; add a reference to System.DirectoryServices.AccountManagement.dll. The code above works unchanged apart from the C# 12 syntax (primary constructor and using declarations), which you can rewrite as a normal constructor and using blocks.