Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Integration and Security

Application Authentication with LDAP: Search, Then Bind

Integrate your application with Active Directory login: the search-then-bind pattern, service accounts, group checks, LDAP filter and DN escaping against injection, paging and caching.

Almost every internal application eventually needs to answer the question "is this person who they say they are, and which groups are they in?". Instead of storing passwords in its own database, the application asks the directory. Done well, users keep one password and administrators control access in one place. Done badly, you get LDAP injection, a login page that lets in anyone, or a service account with far too much power.

This lesson explains the standard pattern, the safety rules and the group-check strategies. The directory itself cannot run on this site, so the examples are a small in-memory directory that imitates the behaviour, plus read-only snippets with the real ldap3 Python library, clearly marked.

The search-then-bind pattern

Users type alice or [email protected], but an LDAP bind needs a DN (or a UPN, which Active Directory also accepts). The robust method has four steps:

  1. Connect with TLS (LDAPS or StartTLS).
  2. Bind as a service account that has read access to the user OUs.
  3. Search for the user entry with a filter built from the typed name, requesting only the attributes you need, such as distinguishedName, displayName, mail and memberOf. Insist on exactly one result.
  4. Bind again as that user with the DN found and the typed password. Success means the password is correct. Then read groups and close the connection.

Why not bind directly with DOMAIN\alice? You can, and for simple apps with AD only it is fine. But search-then-bind works in any LDAP directory, lets you reject disabled accounts and lets you enforce extra rules on the entry before accepting the login.

sequenceDiagram
  participant A as App
  participant D as Directory
  A->>D: bind as svc-app (read-only)
  A->>D: search (&(objectClass=user)(sAMAccountName=alice))
  D->>A: one entry with DN
  A->>D: bind as that DN with typed password
  D->>A: success or invalidCredentials

Never build filters with string concatenation

If the login code does "(sAMAccountName=" + username + ")", a user who types * matches everyone, and *)(objectClass=* can rewrite the filter (LDAP injection). The fix is to escape the five special characters from RFC 4515 in filter values:

Character Escape
* \2a
( \28
) \29
\ \5c
NUL \00

Distinguished names have different rules (RFC 4514): you escape , + " \ < > ; and leading # or spaces with a backslash. Libraries provide helpers (ldap3.utils.conv.escape_filter_chars, ldap3.utils.dn.escape_rdn), and you should use them rather than writing your own. The functions below are shown so you can see exactly what they do.

Python Escape filter and DN values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A complete login flow against a fake directory

The class below behaves like a tiny directory: it supports bind, search by sAMAccountName and group membership. It is not an LDAP client, only a stand-in with the same steps, so you can run and modify the application logic.

Python Search-then-bind with an in-memory directory (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note the careful messages: a real login page should return the same generic text ("invalid user name or password") for unknown users and wrong passwords, to avoid disclosing which accounts exist. The distinct messages above are for learning only.

The same flow with the ldap3 library (read-only)

Python
from ldap3 import Server, Connection, Tls, SUBTREE
from ldap3.utils.conv import escape_filter_chars
import ssl

server = Server("ldaps://dc1.example.com", tls=Tls(validate=ssl.CERT_REQUIRED))
svc = Connection(server, "[email protected]", SERVICE_PASSWORD, auto_bind=True)

svc.search("ou=staff,dc=example,dc=com",
           f"(&(objectClass=user)(sAMAccountName={escape_filter_chars(username)}))",
           search_scope=SUBTREE, attributes=["distinguishedName", "memberOf"], size_limit=2)
if len(svc.entries) != 1:
    raise LoginError("unknown user")

user = Connection(server, svc.entries[0].entry_dn, typed_password)
if not user.bind():
    raise LoginError("bad credentials")

Take the service password from a secret store, not source code. Python's ldap3 is a third-party package that you install yourself; it is not available in the browser runner.

Checking groups

There are three common approaches:

  1. Read memberOf on the user entry. Fast, but only lists direct groups and is limited when a user belongs to hundreds of groups (token and attribute size).
  2. Nested membership with the matching-rule OID. Active Directory evaluates nested groups server-side with (memberOf:1.2.840.113556.1.4.1941:=cn=Finance,ou=groups,dc=example,dc=com). Use it on the user entry or as a filter: (&(sAMAccountName=alice)(memberOf:1.2.840.113556.1.4.1941:=<groupDN>)). This is called LDAP_MATCHING_RULE_IN_CHAIN and is the usual way to resolve nesting. It is slower on very large directories.
  3. Primary group and token groups. The user's primary group (often Domain Users) is not in memberOf; tokenGroups lists every SID in the token, including nested and primary, and can be read with a base-scope search.

Map the directory groups to roles in the application (for example APP-Finance-Admins to the Admin role) instead of hard-coding user names.

Operational advice

  • Reuse connections or use a pool; opening TLS for every login is expensive.
  • Set timeouts (connect and receive) so a slow DC does not hang your web threads, and configure two or more domain controllers for failover (DNS names or a list).
  • Limit the search base to the user OUs and set size_limit, so a loose filter cannot dump the directory.
  • Handle paging for group member lists beyond 1,500 values (use ranged retrieval or the paged results control).
  • Cache group lookups briefly (a few minutes), not credentials, and never log passwords.
  • Lock-out risk: a loop that retries a wrong password locks the real user's account; count failures in your app.
  • Consider SAML or OpenID Connect (Active Directory Federation Services or Entra ID) for new web apps; LDAP passes the password through your app, while federation does not.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In search-then-bind, why is the first bind done with a service account?

    The application needs read access to locate the entry; the second bind with the typed password is what authenticates the user.
  2. 2. What does the input *)(objectClass=* do in an unescaped filter?

    Unescaped special characters let an attacker inject additional filter terms.
  3. 3. Which approach resolves nested group membership on the server?

    LDAP_MATCHING_RULE_IN_CHAIN walks the group nesting for you.
  4. 4. Why should a login page give the same error for unknown users and wrong passwords?

    Different messages allow account enumeration.

Summary

  • Search with a read-only service account, then bind as the user to verify the password.
  • Always escape filter and DN values with a library helper; never concatenate raw input.
  • Resolve groups with memberOf, the in-chain matching rule or tokenGroups, and map groups to application roles.
  • Use TLS, timeouts, failover, paging, small search bases and a secret store for service credentials.

Next: Linux Integration: realm join and SSSD