Roles & Privileges
PostgreSQL manages authentication and authorization through roles (cluster-wide). Both "users" and "groups" are simply roles — the only difference is whether a role has the LOGIN attribute.
Creating roles and groups#
Follow least privilege by grouping permissions into NOLOGIN roles and granting those group roles to individual login roles:
-- Create a read-only group role
CREATE ROLE app_readonly NOLOGIN;
-- Create a login role and assign it to the group
CREATE ROLE alice LOGIN PASSWORD 'strong_password';
GRANT app_readonly TO alice;
List all roles and their attributes in psql:
\du+Granting schema, table, and future object privileges#
Granting access to a schema requires USAGE on the schema and privileges on the objects inside it:
GRANT CONNECT ON DATABASE mydb TO app_readonly;
GRANT USAGE ON SCHEMA public TO app_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO app_readonly;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO app_readonly;
To ensure future tables created by a deployment role (e.g., app_owner) automatically inherit read permissions, set default privileges:
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT SELECT ON TABLES TO app_readonly;
ALTER DEFAULT PRIVILEGESonly applies to objects created by the specifiedFOR ROLE(or the current user if omitted) — it does not change privileges on already existing tables.
Useful predefined roles#
PostgreSQL ships with built-in roles so you rarely need to hand out SUPERUSER:
| Predefined Role | Purpose |
|---|---|
pg_monitor | Read access to monitoring views and statistics (ideal for Prometheus exporters). |
pg_read_all_data | Read all tables, views, and sequences across all schemas without SUPERUSER. |
pg_write_all_data | Write access across all tables and schemas. |
pg_read_all_stats | Read all pg_stat_* views (included in pg_monitor). |
pg_signal_backend | Cancel queries or terminate non-superuser backends (pg_cancel_backend, pg_terminate_backend). |
Example:
GRANT pg_read_all_data TO reporting_user;Client authentication (pg_hba.conf)#
pg_hba.conf controls who can connect, from where, to which database, and how they authenticate. Rules are evaluated top-to-bottom (first match wins):
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer
hostssl mydb app_user 10.0.0.0/24 scram-sha-256
host all all 0.0.0.0/0 reject
After editing pg_hba.conf, reload without restarting PostgreSQL and verify no syntax errors occurred:
SELECT pg_reload_conf();
SELECT line_number, type, database, user_name, address, auth_method, error
FROM pg_hba_file_rules;