Sub topic 2
Choosing an authentication method
This chapter assumes you know basic SQL and psql, can edit files on a Linux server, and read CIDR notation such as 10.0.0.0/24. Authentication checks who is connecting. Authorization, which comes later, checks what that role may do. The file pg_hba.conf (host-based authentication) maps each incoming connection to an authentication method.
Choosing an authentication method
Each record in pg_hba.conf names a connection type, database, user, address, and method. Use peer for local superuser access over the Unix socket, scram-sha-256 for password logins, and reject to refuse a match. PostgreSQL reads the file from top to bottom and uses the first matching record, so place specific rules above general ones. Use hostssl for remote connections that cross a network.
How passwords are stored
PostgreSQL stores role passwords as hashes in the system catalog pg_authid, never as plain text. The password_encryption setting chooses the hash type when a password is set. Since PostgreSQL 14, the default is scram-sha-256. Older databases may still hold MD5 hashes, which start with md5.
How SCRAM-SHA-256 works
SCRAM (Salted Challenge Response Authentication Mechanism) is a challenge-response protocol. The server stores a salted, iterated verifier instead of the password. During login, the client and server exchange random nonces and proofs. The password itself never travels over the network, and the server checks the client's proof against the stored verifier.
Setting up SCRAM for roles and rules
Set the hashing method, then set the role password so it is stored as a SCRAM verifier:
SET password_encryption = 'scram-sha-256';
\password app_user
SELECT rolname, left(rolpassword, 14) AS stored_prefix
FROM pg_authid
WHERE rolname = 'app_user';The stored prefix should read SCRAM-SHA-256$. Then point the matching rule at SCRAM:
host appdb app_user 10.0.0.0/24 scram-sha-256Exercise
A client at 10.0.0.5 connects to appdb as appuser. The file contains this order: "host all all 0.0.0.0/0 reject" first, then "host appdb appuser 10.0.0.0/24 scram-sha-256". Which rule applies, and why?
Show answer
The reject rule applies. PostgreSQL uses the first matching record, and 0.0.0.0/0 matches every address, so the connection is refused before the SCRAM rule is checked. Move the specific rule above the reject rule.