PostgreSQL LDAP authentication with Active Directory or OpenLDAP

PostgreSQL can check a password against a directory during login, but the database still decides which roles exist and what they can do. This page covers the bind method, transport security, role design and outage planning.

On this page

How PostgreSQL LDAP authentication with Active Directory or OpenLDAP works

A team that wants one set of directory passwords for database logins can use PostgreSQL's LDAP authentication method. The directory verifies the password, while PostgreSQL keeps its own roles, grants and session rules. When a user connects, PostgreSQL asks the LDAP server (Active Directory or OpenLDAP) whether the supplied password is valid for that account. If the directory accepts it, PostgreSQL lets the session in as the matching database role. The directory never decides which tables a user can read or whether that user can create objects. Those permissions stay in PostgreSQL, so every login still needs a role that already exists in the cluster with the grants it requires. The LDAP method is described in the PostgreSQL authentication methods documentation, which is the starting point for the configuration choices that follow.

Teams usually choose LDAP over local database passwords when they want one place to disable a leaver, reset a password or enforce a directory password policy, and when the number of people or service accounts needing database access makes separate PostgreSQL password lists hard to maintain. It is a reasonable fit for interactive users connecting from clients that send a password. It is less suitable for services that cannot be rotated easily, and it does not remove the need for TLS, since the password crosses the network to the server and on to the directory. Teams that run Windows-integrated single sign-on, or that want users to connect without typing a password at all, should look at Kerberos instead. That option is covered in the sibling Kerberos page. Before choosing, confirm which directory your organization operates, whether its password rules and account states are reliable enough to be the single source of truth, and who will own the directory account lifecycle.

Which LDAP options fit which directory and environment

This table compares the LDAP connection patterns PostgreSQL can use against Active Directory, OpenLDAP and FreeIPA. Read each row as a decision: the fit, what the directory team must provide, and the trade-off you accept. Confirm exact pg_hba.conf LDAP keys against your PostgreSQL version in the authentication docs before you write rules.

OptionBest fitWhat the directory team providesMain trade-off
Simple bind (direct DN construction)Single directory with one predictable naming pattern, such as one OU for all database usersA DN pattern for users, a confirmed bind rule, and agreement that the DN format will not changeBreaks when users sit in several OUs or when the login name differs from the directory account name
Search+bindUsers spread across OUs, or login names that differ from the account DNA read-only service account, a search base, and the attribute holding the login name (for example sAMAccountName in Active Directory or uid in OpenLDAP)Needs a service account whose password must be stored and rotated, and a directory query on every login
LDAPS (TLS on port 636)Any production use where the password crosses the networkA certificate for the domain controller or LDAP server that PostgreSQL clients can validate, and the CA chainCertificate expiry and CA trust become database login outages if nobody owns renewal
StartTLS on the LDAP connectionDirectories that offer StartTLS but not a dedicated LDAPS listenerStartTLS enabled on the directory and a validated certificateUpgrade step can be bypassed or misconfigured, so confirm the connection is encrypted before go-live
Active Directory as the directoryWindows-centric organizations where staff already log in with domain accountsService account with minimal read rights, search base covering the database user OUs, and a plan for disabled or locked accountsPassword checks depend on domain controller availability, and Linux or Windows Kerberos options may suit it better
OpenLDAP as the directoryOrganizations running their own LDAP tree without Windows dependenciesSchema and attribute names documented, a bind account, and replication or failover of the LDAP serviceAttribute and schema choices are local, so each deployment needs its own verification
FreeIPA as the directoryLinux-centric estates that want LDAP plus Kerberos, certificates and host policy from one systemA user search base in the IdM tree, a bind identity, and a decision on whether Kerberos (GSSAPI) replaces LDAP passwordsAdds a full identity system to operate, and password-based LDAP still sends credentials to the directory

A login crosses the trust boundary only after pg_hba.conf matches

The flow starts with a client sending a username and password to PostgreSQL over its connection. PostgreSQL matches the connection against the pg_hba.conf rule, then contacts the directory over LDAPS or StartTLS. With search+bind, a separate search account first finds the user's distinguished name. The directory returns success or failure, and PostgreSQL still checks that a matching role exists before the session starts. The boundary between the database host and the directory is where to verify encryption and account scope.

Login path from client to directory, with the search account used only in search+bind.

What changes when the directory is Active Directory, OpenLDAP or FreeIPA

Active Directory is the most common directory in regulated organizations, and it is the one most teams assume PostgreSQL can use directly. Its user objects carry several login names, so the attribute you bind or search on determines whether a login succeeds. Domain controllers replicate directory data to each other, which means the LDAP host you point PostgreSQL at can be any domain controller, and the certificate that domain controller presents must chain to a CA that your PostgreSQL server trusts.

  • Login attribute: sAMAccountName is the pre-Windows 2000 logon name and is unique within a domain. userPrincipalName uses the user@domain form. Pick one and test it for every account type, including service accounts.
  • Search base and filter: In search+bind mode, scope the search to the OUs that hold database users so that disabled or out-of-scope accounts do not authenticate.
  • LDAPS certificate chain: Domain controller certificates must chain to a CA the PostgreSQL host trusts, with the full chain installed. Confirm the certificate subject matches the name you connect to.
  • Multiple domain controllers: Plan a list of LDAP servers so that one domain controller outage does not stop logins.
  • Linux limits: Microsoft's comparison notes that Linux machines need third-party tools or Kerberos realm configuration to authenticate against Active Directory, so do not assume a Linux host joins the domain.

Confirm the attribute, OU scope and certificate chain with your Active Directory team before you write the rule.

How to set up LDAP login in the right order

This sequence takes PostgreSQL from an unverified directory connection to a tested login path, where only in-scope users can connect and every failure is rejected and logged. Each step ends with a check, so a problem is caught before the next layer depends on it.

  1. Confirm the directory and its LDAPS certificate chain

    Identify the domain controllers or OpenLDAP servers the database should use, and confirm which certificate authority issued their LDAPS certificate. Export the CA chain your team trusts and install it on the PostgreSQL host, in the trust location your Linux distribution uses for system certificates. Then test from the database host itself, using a standard LDAP client against port 636 with the chain in place. The step is done when the TLS handshake succeeds and the certificate name matches the hostname you will put in the PostgreSQL configuration.

  2. Create a read-only directory account for lookups

    Ask the directory team to create a dedicated service account that can read user objects in the search base and nothing more. Do not reuse a personal admin account or a account with password-change rights. Record its distinguished name and store the password in your secrets manager, not in a shared file. The step is done when a test search from the database host returns the expected test user and the service account cannot modify any object, which the directory team can confirm with a write attempt that is refused.

  3. Choose simple bind or search and bind

    Decide how PostgreSQL turns a username into a directory identity. Simple bind builds the user's distinguished name from a pattern and binds with the password directly, which needs one predictable naming scheme. Search and bind first finds the user's entry with the read-only account, then binds as that entry, which handles users whose names do not follow a pattern and is usually the better fit for Active Directory, where accounts are often found by sAMAccountName. Write the choice and the search base down before editing any configuration, since the rest of the sequence depends on it.

  4. Create the matching PostgreSQL roles

    LDAP checks the password only. PostgreSQL still needs a role with the same name, and that role still holds all the privileges. For each directory user or group who should connect, create a login role with no password and no superuser attribute, then grant only the database and schema privileges that user needs. Confirm each role with a query against the catalog. A user without a matching role will authenticate in the directory and still be refused by PostgreSQL, so this check catches a common gap before testing begins.

  5. Add the narrowest pg_hba.conf rule

    Add an hostssl line to pg_hba.conf with the ldap method, limiting the address to the client subnet that needs access and the database to the one database in scope. Set the LDAP server, port 636, the base DN, and either the bind pattern or the search filter and service account, depending on the decision in the earlier step. Keep rules that allow broader access in place only until testing passes, then remove them. The rule should appear above any general fallback line, because PostgreSQL uses the first matching record. Confirm the file parses by checking the server log after reload.

  6. Reload the configuration without a restart

    Reload PostgreSQL so it reads the new authentication rules, using the service manager or pg_ctl reload instead of a restart. Keep the current session open while testing, so a bad rule can be reverted without losing the only administrative connection. Check the server log for configuration errors and confirm that the LDAP parameters were accepted. The step is done when the server reports the reload succeeded and a new connection attempt reaches the LDAP check rather than failing on a syntax or address error.

  7. Test an in-scope user and an out-of-scope user

    Connect as a user who has both a directory account and a matching PostgreSQL role, and confirm the session opens with the expected privileges. Then test a directory user who is outside the allowed group or subnet, and a user with a wrong password. Each of these must be refused. Read the PostgreSQL server log for the refusals and confirm each one is recorded with a reason. Finally, stop the test LDAP server or block its port from the database host and confirm a login attempt fails rather than succeeding. Record the results so the team can repeat the same checks after upgrades or directory changes.

Security controls to plan before LDAP login goes live

LDAP authentication moves password checks out of PostgreSQL and into your directory, so the security of each login depends on the link to the directory, the account PostgreSQL uses to query it, and the rules that decide which connections reach the password check at all. Confirm each control below against your own directory and the PostgreSQL version you run.

Transport encryption and certificate validation

Simple bind sends the user's password to the directory, so the connection must be protected. Choose LDAPS on port 636 or StartTLS, and configure PostgreSQL to validate the directory's certificate chain against your internal CA rather than accepting any certificate. Check the authentication settings for ldaptls and the certificate trust store on the PostgreSQL server, and test with a deliberately wrong CA to confirm that the connection is refused.

Authentication methods docs

Bind account least privilege

For search+bind, PostgreSQL uses a service account to find the user's distinguished name before it attempts the user's bind. Give that account read access only to the user search base and the attributes needed for lookup, and deny it write access, group administration and password reset rights. Ask your directory team for a documented rotation schedule and a rotation procedure that updates the PostgreSQL configuration without a long outage.

pg_hba.conf rule order and fallbacks

PostgreSQL evaluates pg_hba.conf entries from the top and uses the first entry that matches, so an earlier trust or md5 line can bypass the LDAP rule you intended. Remove trust entries, retire md5 in favor of scram-sha-256, and place the ldap entries with hostssl and narrow address ranges. Keep a single documented fallback for emergency access, and test each rule with a client from the intended network and from an outside address.

Authentication methods docs

Logging on both sides

Failed and successful logins must be visible in two places: the PostgreSQL server log, where connection attempts and rejections appear when logging settings capture them, and the directory's security log, where bind failures, lockouts and account changes are recorded. Confirm which events each side records in your version, decide who reviews them, and forward both streams to the system your security team uses. Without the directory side, a password spray that never reaches PostgreSQL can go unseen.

Separate admin and replication access

Directory login is convenient, which makes it tempting to use it for superuser and replication roles. Keep those roles on local, certificate or Kerberos authentication with restricted addresses, so that a compromised directory account cannot become a database administrator or a replication client. Confirm that replication entries in pg_hba.conf name the replication pseudo-database and do not fall under the general LDAP rule, and that break-glass credentials are stored outside the directory.

Password policy enforced by the directory

PostgreSQL does not check password strength, expiry or lockout for LDAP users, because the directory validates the password at bind time. Confirm that your directory enforces length, complexity, history, expiry and account lockout for the accounts that log in to PostgreSQL, and that disabled or departed users fail their next bind. Remember that a role left behind in PostgreSQL still exists after the directory account is removed, so review role inventory on a schedule.

Why PostgreSQL roles still have to exist

A directory can confirm who someone is, but it cannot grant anything inside PostgreSQL. Once LDAP has verified a password, PostgreSQL still needs a role that owns the privileges for that person or group, and the login only succeeds if a matching role already exists. Every directory user or group you allow to connect therefore needs a planned role with explicit grants on databases, schemas and tables. Treat the directory as the source of truth for identity and the database role catalog as the source of truth for what that identity can do.

The main operational risk is role drift. Directory accounts are removed when staff leave or change teams, but database roles, their memberships and their default privileges are not removed automatically. Over time, orphaned roles remain with live grants, and a former employee's directory account may be disabled while the database role still holds access to data. Ask who owns the process that reconciles roles against directory groups, how often it runs, and whether it removes or only reports orphaned roles. Also confirm whether any roles can be used with a password set directly in PostgreSQL, since that path bypasses the directory.

Mapping one role per person is simple to audit but multiplies grants and makes reviews slow. Mapping directory groups to shared group roles, with individual users granted membership, keeps privileges in one place and matches how access reviews are usually run. The choice should follow your least-privilege design: separate owner roles that hold schema objects from application and reporting roles that only receive the rights they need, and keep administrative roles out of general directory groups. Decide the role plan before the first LDAP rule is written, because retrofitting group roles onto years of individual grants is much harder than designing them up front.

What happens when the directory is down or slow

Once PostgreSQL checks passwords against a directory, the directory becomes part of every login path. The cards below cover the failures that most often surprise teams, and the planning step that limits each one before an outage forces the decision.

Total login rejection during an outage

When the directory or its network path is unreachable, every role configured for LDAP fails to connect at once, including people who need to fix the problem. The planning step is a documented break-glass path: a local role authenticated by a method that does not depend on the directory, such as a certificate or a locally managed password held in a sealed vault. Test that path in a drill, and confirm which methods your pg_hba.conf rules keep available during a directory outage.

PostgreSQL auth methods

Slow logins from timeouts

A directory that is reachable but slow holds each connection attempt open until the LDAP client times out, so application pools and admin sessions stall together. Set explicit connect and search timeouts in the PostgreSQL LDAP settings rather than relying on defaults, and measure how long a failed bind takes from the database host. Ask the directory team what their own response targets are, because a PostgreSQL timeout longer than the application's connection timeout turns a slow directory into an application outage.

Pooler sessions holding the directory open

A pooler such as PgBouncer keeps server connections open for reuse, so a burst of logins can fill its pool with sessions that are waiting on authentication or that were authenticated against an earlier directory state. Size the pool for the expected peak, set client and server connection limits deliberately, and check what PgBouncer's authentication settings do with your LDAP-backed roles before a go-live. Confirm the behavior in the PgBouncer version you run, since security fixes are released between versions.

PgBouncer project site

Expired bind account password

PostgreSQL does not use a bind account in simple bind mode, but search+bind mode needs a directory account that can search for user entries, and that account's password can expire under a directory policy. When it does, every LDAP login fails with an error that looks like a bad password. Record the bind account's expiry date and owner, set a password rotation procedure with a reminder before expiry, and alert on repeated bind failures from the database host so the cause is visible within minutes.

Certificate expiry breaking LDAPS

Connections that use LDAPS validate the directory server's certificate against the CA trusted by the PostgreSQL host. When the server certificate or the issuing CA certificate expires, or the chain changes after a directory rebuild, logins fail at the TLS step and the error may not name the certificate. Track expiry dates for each domain controller or LDAP server certificate, confirm the trusted CA file on each PostgreSQL node, and test an LDAPS connection after every certificate rotation on the directory side.

Stale fallback rules in pg_hba.conf

If pg_hba.conf carries an older password or trust rule below the LDAP entry, a login that the directory would reject, or a role that should have been retired, can still succeed through the fallback. An attacker who finds that path does not need to defeat the directory at all. Review rule order during each change, remove entries that no longer serve a documented purpose, and confirm with a test login from each source network that the intended method is the only one that matches.

Authentication methods docs

When Kerberos may be the better choice than LDAP passwords

LDAP login still sends a password to the database for checking, even when the directory performs the verification. The user types a password, PostgreSQL passes it to the directory through its LDAP method, and the directory confirms it. Kerberos works differently. With GSSAPI, a user who already holds a domain ticket connects without typing a password, and the database trusts the ticket that the Key Distribution Center issued. If your users sign in to Windows and expect the same single sign-on for database tools, Kerberos removes a credential exchange that LDAP cannot. Microsoft's comparison of Active Directory and Entra ID notes that most on-premises apps authenticate against Active Directory through LDAP, Windows-integrated authentication based on NTLM and Kerberos, or header-based authentication. Your application mix determines which of those paths your team already maintains.

The decision rests on three questions. First, what is your client mix? If most connections come from Windows workstations with domain-joined analysts, and from services that run on Windows, Kerberos fits naturally. If many clients are Linux servers, containers or tools that cannot obtain tickets easily, LDAP may remain the simpler path. Second, are your Linux hosts ready? Microsoft's comparison says Linux machines need third-party tools or must be configured to authenticate against Active Directory as a Kerberos realm. FreeIPA can establish a cross-forest trust so Active Directory users reach Linux resources, and its documentation covers Kerberos single sign-on for Linux clients. Confirm the realm, DNS and time synchronization on each host before you commit. Third, is a password exchange acceptable? Many security teams accept LDAP only with LDAPS and a narrow bind account, and treat the password exchange as a residual risk.

If Kerberos looks like the better fit, keep the LDAP design as a fallback until you have tested ticket-based login for every client type. The implementation steps, including service principals, keytabs, pg_ident.conf mapping and GSSAPI encryption, are covered in PostgreSQL Kerberos single sign-on with Active Directory. Plan a test matrix that covers each application, admin tool and service account, and confirm with your directory team which accounts can receive service principals. Expect the existing LDAP roles in PostgreSQL to remain, because Kerberos principals must still map to database roles.

Questions buyers ask before they hire help with LDAP login

What drives the cost of PostgreSQL LDAP authentication work?

The cost follows the written scope, and the main drivers are the number of directories, how much LDAPS certificate work is needed, the size of the role model, the number of pg_hba.conf rules that must change, and how far testing goes. Each directory adds its own bind path, failure behavior and test users. LDAPS work depends on whether an internal certificate authority already issues certificates the directory trusts, and on how many PostgreSQL servers and poolers need the chain. The role model matters because every database role that people use must exist in PostgreSQL, so a large set of roles means more mapping and review. Testing scope covers successful logins, wrong passwords, a directory outage and the fallback path. Most engagements are fixed-scope, so ask for a quote that lists each of these items, the deliverables and the timeline in writing before work starts. DeployOpen does not publish a price list.

How long does a PostgreSQL LDAP login project take?

The duration depends on the number of directories, the state of the certificate chain, how many roles and rules change, and how many change windows the client can schedule. A single Active Directory domain with an existing internal certificate authority is usually the shortest case, while several OpenLDAP instances or a missing certificate chain add steps. Confirm the timeline with DeployOpen against your written scope, and ask for the dependencies that could delay it, such as directory admin approvals and the date of the first production change window. No fixed duration is set here because none has been researched for this work.

What must our team provide before the work starts?

Plan to provide these items before the first session:

  • Directory administrator access, or a named administrator who can create and test the bind account and group lookups
  • A dedicated, low-privilege service account for search and bind, with its password held in your secrets process
  • The full certificate chain for the LDAPS endpoint, including the internal root and any intermediates, plus the hostnames the certificate covers
  • Test users in each directory, including one account that should fail, one locked or disabled account and one account in a group that should map to a role
  • A change window for pg_hba.conf and PostgreSQL reloads, along with a rollback owner

These items often take longer to arrange than the technical work, so request them early.

Can our internal team set up PostgreSQL LDAP login alone?

A team with PostgreSQL and directory experience can build it alone, and many do. Teams usually stumble in four places: choosing between simple bind and search+bind and getting the search filter right, trusting an LDAPS certificate that the database host does not yet recognize, forgetting that PostgreSQL still needs a role for each user and that a directory login does not grant privileges, and not planning for a directory outage. A common gap is testing only the successful path. Your team can run the work alone if it has time for a full test cycle, a rollback plan and someone who owns the directory side. If any of those are missing, a fixed-scope engagement covers them as written deliverables.

Should we replace LDAP password checks with Kerberos?

Kerberos is often the better choice when users sit on domain-joined Windows or Linux clients and you want passwordless login, since the client gets a ticket instead of sending a password to the database. LDAP password checks are simpler to deploy and work with clients that cannot obtain Kerberos tickets. Microsoft notes that Linux machines need third-party tools or a Kerberos realm configuration to authenticate against Active Directory, so check your client mix first. FreeIPA can establish a cross-forest trust with Active Directory, which is one option if you run Linux services alongside a Windows domain. The Kerberos single sign-on page in this series covers that path, and the choice should follow your client environment rather than a general preference.

What does a fixed-scope quote for this work include?

Ask for a written scope that names each directory, the authentication method (simple bind or search+bind), the LDAPS setup and certificate chain handling, the list of PostgreSQL roles and pg_hba.conf rules to change, the test cases including directory outage behavior, the handover documents and the retest after changes. The quote should state what the client must provide, the timeline assumptions and what is excluded, such as changes to the directory itself. Confirm how change requests are priced if the scope grows. Ongoing support and upgrades are separate retainers. DeployOpen issues the quote after the written scope is agreed, and DeployOpen does not publish a price list.

Limits to confirm in your environment

LDAP authentication moves part of PostgreSQL's login path into a directory you may not control. The items below are things to confirm against your PostgreSQL version, your directory configuration and your operating model before any production rollout.

LDAP options in your PostgreSQL version

The LDAP settings available in pg_hba.conf depend on the PostgreSQL major and minor release you run, and options can differ between simple bind and search+bind modes. Read the client authentication page for your exact version and confirm each parameter you plan to use, including how it handles TLS and the lookup filter. Do not copy settings from an older example without checking them against that version's documentation.

Authentication methods docs

Directory password policy and lockout

PostgreSQL does not enforce password complexity, expiry or account lockout when it delegates a check to LDAP. Those controls come from the directory, so confirm that Active Directory or OpenLDAP enforces your internal password rules and lockout thresholds for accounts used to log in to the database. Also confirm who owns those settings, because a change in the directory changes database access without any change in PostgreSQL.

LDAPS and the trusted certificate chain

Simple bind sends the user's password to the directory on every login, so the connection must be encrypted. Confirm that your directory offers LDAPS on the address PostgreSQL will reach, and that the certificate chain is trusted by the database server's CA store. Test with the exact host name in the certificate, because a mismatch often appears only after a certificate renewal.

Nested groups and role mapping

PostgreSQL roles are not created from directory groups by LDAP authentication, so each database role must already exist. Confirm whether your access model relies on nested groups, because a simple group filter may not reflect membership inherited through another group. Decide whether the database role list is maintained by hand, by a provisioning process, or by an identity governance tool, and confirm who reviews it.

Current minor release and support window

Confirm which PostgreSQL major version you run and whether it is still supported, then check the latest minor release you have applied. The versioning policy describes minor releases at least once every three months, and each major version has a published end date. Authentication fixes arrive in minor releases, so the LDAP setup depends on a patch cadence that someone owns.

Oldest supported major
14
Versioning policy

Support model for directory outages

When the directory is unreachable, new logins fail, and the behavior of existing sessions and of service accounts depends on your configuration. Confirm who on your team responds when the directory is down, whether a break-glass database account exists and is tested, and what your recovery time expectation is for login. Confirm these with your operations owners before go-live.

How DeployOpen works on this

DeployOpen plans, builds and documents PostgreSQL LDAP authentication inside your own infrastructure, so your directory team, database administrators and security reviewers can see every rule before it reaches production. Work starts from a written scope that names the directory, the PostgreSQL versions and the roles involved, and ends with a handover your team can run without us.

How we scope

  • We confirm the directory type, Active Directory or OpenLDAP, and which domain controllers or LDAP servers PostgreSQL can reach.
  • We agree in writing whether the design uses simple bind or search+bind, and whether LDAPS or StartTLS is required.
  • We list which PostgreSQL roles must exist beforehand, and who owns the mapping from directory groups to those roles.

How we build

  • We configure pg_hba.conf entries for LDAP on test clusters first, with narrowed addresses, databases and users, and no trust entries.
  • We verify LDAPS certificate chains, the bind account permissions and the search filters against your directory before any production change.
  • We test what happens when the directory is slow or unreachable, and document the access behavior your team should expect.

How we hand over

  • You receive the final pg_hba.conf rules, configuration files and a runbook for reloading PostgreSQL safely after changes.
  • You receive a test log showing successful logins, rejected logins, and the directory outage behavior we observed.
  • You receive a decision record covering the simple bind versus search+bind choice, Kerberos as an alternative, and open risks to confirm.

How we support

  • Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts.
  • Ongoing support, upgrades and continuous testing are available as a retainer, including retesting after directory or PostgreSQL upgrades.
  • We recommend asking for a quote that separates one-time build work from any recurring support, so your budget reflects both.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.