IC Improve Code Recipes

Recipe 7.5 · Python

Active Directory Lookups with System.DirectoryServices.AccountManagement

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

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.

Requirements: Python 3.12+. Install: pip install ldap3 · Needs at run time: an Active Directory / LDAP domain controller. The module loads without them; calling the code does not work without them.

Python LDAP lookup with a hand-built, injectable filter (p153_r7_5_ldap_string_filter_before.py)
"""LDAP lookup with a hand-built, injectable filter

Source: ImproveCode, Chapter 7, Recipe 7.5 "Active Directory Lookups with System.DirectoryServices.AccountManagement"
Section: The way it's often written
Book page: 153  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
ldap3 replaces DirectoryEntry/DirectorySearcher; the connection is never unbound.
"""

from ldap3 import Connection, Server


def get_email(user_name: str) -> str:
    # Not this: hand-built filter (injectable), nothing disposed.
    root = Connection(Server("ldap://corp.local"), auto_bind=True)
    root.search("DC=corp,DC=local",
                "(&(objectClass=user)(sAMAccountName=" + user_name + "))",
                attributes=["mail"], size_limit=1)
    result = root.entries[0]
    return str(result["mail"][0])

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.

Usage:

Requirements: Python 3.12+. Install: pip install ldap3 · Needs at run time: an Active Directory / LDAP domain controller. The module loads without them; calling the code does not work without them.

Python Active Directory user lookup, nested groups and credential validation (p154_r7_5_active_directory_user_lookup.py)
"""Active Directory user lookup, nested groups and credential validation

Source: ImproveCode, Chapter 7, Recipe 7.5 "Active Directory Lookups with System.DirectoryServices.AccountManagement"
Section: The improved recipe
Book page: 154-155  -- original C# listing
Converted from C# to Python.
ldap3 replaces PrincipalContext/UserPrincipal (cross-platform, so no Windows guard);
escape_filter_chars keeps filters safe, the LDAP_MATCHING_RULE_IN_CHAIN OID gives
nested groups. Released ldap3 (2.9.x) cannot sign/seal an NTLM bind, so credential
validation binds over LDAPS (TLS, port 636) to protect the password instead of
Negotiate|Signing|Sealing.
"""

from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass

from ldap3 import NTLM, SUBTREE, Connection, Server
from ldap3.core.exceptions import LDAPException
from ldap3.utils.conv import escape_filter_chars

_ACCOUNT_DISABLE = 0x2


@dataclass(frozen=True)
class DirectoryUser:
    sam_account_name: str
    display_name: str | None
    email: str | None
    is_enabled: bool


class DirectoryLookup:
    def __init__(self, domain: str, container: str | None = None,
                 bind_user: str | None = None,
                 bind_password: str | None = None) -> None:
        self._domain = domain
        self._container = container or ",".join(
            f"DC={part}" for part in domain.split("."))
        self._bind_user = bind_user
        self._bind_password = bind_password

    def find_user(self, sam_account_name: str) -> DirectoryUser | None:
        if not sam_account_name or not sam_account_name.strip():
            raise ValueError("sam_account_name")

        with self._create_context() as conn:
            entry = self._find_entry(conn, sam_account_name)
            if entry is None:
                return None
            attrs = entry["attributes"]
            uac = int(attrs.get("userAccountControl") or 0)
            return DirectoryUser(
                attrs.get("sAMAccountName"),
                attrs.get("displayName") or None,
                attrs.get("mail") or None,
                not (uac & _ACCOUNT_DISABLE))

    def get_security_groups(self, sam_account_name: str) -> list[str]:
        """Security groups, including nested membership."""
        if not sam_account_name or not sam_account_name.strip():
            raise ValueError("sam_account_name")

        with self._create_context() as conn:
            entry = self._find_entry(conn, sam_account_name)
            if entry is None:
                return []

            user_dn = escape_filter_chars(entry["dn"])
            conn.search(
                self._container,
                "(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=2147483648)"
                f"(member:1.2.840.113556.1.4.1941:={user_dn}))",
                SUBTREE, attributes=["cn"])
            return [e["attributes"]["cn"] for e in conn.response
                    if e.get("type") == "searchResEntry"
                    and e["attributes"].get("cn")]

    def validate_credentials(self, user_name: str, password: str) -> bool:
        if not user_name or not user_name.strip() or not password:
            return False  # an empty password can bind anonymously

        try:
            conn = Connection(
                Server(self._domain, port=636, use_ssl=True),
                user=f"{self._domain}\\{user_name}",
                password=password, authentication=NTLM)
            try:
                return bool(conn.bind())
            finally:
                conn.unbind()
        except LDAPException:
            return False

    def _find_entry(self, conn: Connection, sam: str) -> dict | None:
        conn.search(
            self._container,
            f"(&(objectClass=user)(sAMAccountName={escape_filter_chars(sam)}))",
            SUBTREE,
            attributes=["sAMAccountName", "displayName", "mail",
                        "userAccountControl"],
            size_limit=1)
        entries = [e for e in conn.response if e.get("type") == "searchResEntry"]
        return entries[0] if entries else None

    @contextmanager
    def _create_context(self) -> Iterator[Connection]:
        conn = Connection(
            Server(self._domain), user=self._bind_user,
            password=self._bind_password,
            authentication=NTLM if self._bind_user else None,
            auto_bind=True)
        try:
            yield conn
        finally:
            conn.unbind()

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Looking up a user and their groups with DirectoryLookup (p155_r7_5_directory_lookup_usage.py)
"""Looking up a user and their groups with DirectoryLookup

Source: ImproveCode, Chapter 7, Recipe 7.5 "Active Directory Lookups with System.DirectoryServices.AccountManagement"
Section: The improved recipe
Book page: 155  -- original C# listing
Converted from C# to Python.
The OperatingSystem.IsWindows() guard is kept via sys.platform for fidelity,
though the ldap3-based port also runs elsewhere. Fragment wrapped in a function.
"""

import sys

from p154_r7_5_active_directory_user_lookup import DirectoryLookup


def example() -> None:
    if sys.platform == "win32":
        directory = DirectoryLookup("corp.example.com")
        user = directory.find_user("jdoe")
        groups = directory.get_security_groups("jdoe")
        print(user, groups)

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.