How to Configure pg_hba.conf in PostgreSQL for Client Authentication
To configure
pg_hba.conf in PostgreSQL, edit the file to define which clients can connect, from where, to which databases, and using what authentication method. Each line specifies connection type, client IP range, database, user, and authentication method. After changes, reload PostgreSQL to apply the new settings.Syntax
The pg_hba.conf file uses lines with fields to control client authentication. Each line has these parts:
- TYPE: Connection type, like
local(Unix socket) orhost(TCP/IP). - DATABASE: Which database(s) the rule applies to, e.g.,
allor a specific name. - USER: Which database user(s) the rule applies to, e.g.,
allor a username. - ADDRESS: Client IP address range allowed (for
hosttype), e.g.,192.168.1.0/24. - METHOD: Authentication method, like
md5,trust, orpeer.
plaintext
TYPE DATABASE USER ADDRESS METHOD host all all 192.168.1.0/24 md5
Example
This example allows local connections without a password and requires password authentication for remote clients in the 192.168.1.0/24 network.
plaintext
# Allow local connections via Unix socket without password local all all trust # Allow remote connections from 192.168.1.0/24 with password host all all 192.168.1.0/24 md5
Common Pitfalls
Common mistakes when configuring pg_hba.conf include:
- Forgetting to reload PostgreSQL after changes, so new rules don't apply.
- Using incorrect IP address formats or subnet masks.
- Setting
trustmethod unintentionally, which allows connections without passwords. - Ordering rules incorrectly; PostgreSQL uses the first matching rule.
plaintext
Wrong: host all all 192.168.1.0/24 md5 host all all 0.0.0.0/0 trust Right: host all all 0.0.0.0/0 md5 host all all 192.168.1.0/24 trust
Quick Reference
| Field | Description | Example Values |
|---|---|---|
| TYPE | Connection type | local, host, hostssl, hostnossl |
| DATABASE | Database name(s) | all, mydb, sameuser |
| USER | Database user(s) | all, postgres, alice |
| ADDRESS | Client IP address range (for host types) | 192.168.1.0/24, 10.0.0.0/8 |
| METHOD | Authentication method | trust, md5, peer, scram-sha-256 |
Key Takeaways
Edit
pg_hba.conf to control who can connect, from where, and how they authenticate.Each line defines connection type, database, user, client address, and authentication method.
Order of lines matters; PostgreSQL uses the first matching rule.
Always reload PostgreSQL after editing
pg_hba.conf to apply changes.Avoid using
trust unless you want passwordless access.