Log inSign up

Role-based access control in PostgreSQL

Create a NOLOGIN owner role that owns the schema, grant table rights to group roles such as shop_rw and shop_ro, and give each login role membership in the group it needs. Run ALTER DEFAULT PRIVILEGES so future tables inherit the same rights, keep password_encryption = scram-sha-256 with matching pg_hba.conf lines, and use pgcrypto with bcrypt when the database itself must hash application passwords.

Topic: Databases · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

What is a role in PostgreSQL?

A role is a single concept that covers both users and groups: a role with the LOGIN attribute can connect, and any role can be granted to another role so the member inherits its rights. CREATE USER is just CREATE ROLE ... LOGIN.

Roles belong to the whole cluster, not to one database, while privileges are granted on objects inside databases. That split explains most surprises: a role can exist yet have no right to connect to a database, or connect but see no tables.

The examples run in psql as the postgres superuser (sudo -u postgres psql) on PostgreSQL 15 to 18, as shipped on Ubuntu 24.04, Debian 12 and 13, and available on Rocky Linux and AlmaLinux through module streams or the upstream repository. Install steps live in the PostgreSQL guide. Handy meta-commands for this topic: \du lists roles, \dp shows table privileges and \ddp shows default privileges.

How should you lay out roles for an application?

Use three layers: an owner role that nobody logs in as, group roles that carry rights, and login roles for people and services. Ownership of tables then never sits with an account an attacker could steal.

CREATE ROLE shop_owner NOLOGIN;
CREATE ROLE shop_rw NOLOGIN;
CREATE ROLE shop_ro NOLOGIN;
CREATE DATABASE shop OWNER shop_owner;
\c shop
CREATE SCHEMA app AUTHORIZATION shop_owner;
CREATE ROLE shop_app LOGIN PASSWORD NULL IN ROLE shop_rw;
CREATE ROLE analyst LOGIN PASSWORD NULL IN ROLE shop_ro CONNECTION LIMIT 5;
\password shop_app
\password analyst

The \password command prompts for the secret and sends only its hash to the server, so the plain text never reaches the server log or your shell history. Migrations run as a deploy role that is a member of shop_owner and switches with SET ROLE shop_owner; before creating tables, so new objects are always owned by the owner role.

How do you grant database, schema and table rights?

Grant on three levels: CONNECT on the database, USAGE on the schema and the needed statements on the tables and sequences. Remove the default rights of PUBLIC first.

REVOKE ALL ON DATABASE shop FROM PUBLIC;
GRANT CONNECT ON DATABASE shop TO shop_rw, shop_ro;
GRANT USAGE ON SCHEMA app TO shop_rw, shop_ro;
GRANT SELECT ON ALL TABLES IN SCHEMA app TO shop_ro;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA app TO shop_rw;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA app TO shop_rw;

Since PostgreSQL 15, ordinary roles can no longer create objects in the public schema of a new database, which closes an old gap. On a database upgraded from an older version, apply that rule yourself with REVOKE CREATE ON SCHEMA public FROM PUBLIC;. Set the search path so the app finds its tables without prefixes:

ALTER ROLE shop_app IN DATABASE shop SET search_path = app;

How do default privileges cover future tables?

GRANT ... ON ALL TABLES only touches tables that already exist. ALTER DEFAULT PRIVILEGES tells PostgreSQL which rights to add automatically whenever a given role creates a new object.

ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA app
  GRANT SELECT ON TABLES TO shop_ro;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA app
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO shop_rw;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA app
  GRANT USAGE, SELECT ON SEQUENCES TO shop_rw;
\ddp

The FOR ROLE part matters: default privileges apply only to objects created by that role. If a migration runs as deploy without SET ROLE shop_owner, the new table belongs to deploy, the defaults do not fire and the app gets permission denied. Fix a stray table with ALTER TABLE app.orders OWNER TO shop_owner;.

Which predefined roles save time?

PostgreSQL ships roles for common jobs that cut across databases, so you do not need superuser for them:

  • pg_read_all_data and pg_write_all_data: read or write every table in every database, handy for backup or reporting accounts.
  • pg_monitor: read the statistics views that monitoring agents and tools such as PgHero query.
  • pg_signal_backend: cancel or terminate other sessions.
  • pg_maintain (PostgreSQL 17 and newer): run VACUUM, ANALYZE, REINDEX and similar maintenance on any table.
CREATE ROLE monitor LOGIN PASSWORD NULL IN ROLE pg_monitor;
\password monitor

Since PostgreSQL 16, a role with CREATEROLE can only manage the roles it created or holds ADMIN OPTION on, so you can safely delegate user management to a team lead without handing out superuser.

How do you make sure passwords are stored with SCRAM?

Keep password_encryption = scram-sha-256 (the default since PostgreSQL 14), require scram-sha-256 in pg_hba.conf, and re-set any password still stored as MD5.

SHOW password_encryption;
SELECT rolname, left(rolpassword, 14) AS method
FROM pg_authid WHERE rolpassword IS NOT NULL;

Hashes that start with SCRAM-SHA-256 are good; any that start with md5 need a new password through \password. PostgreSQL 18 marks MD5 passwords as deprecated and warns when one is set, so clear them now. Then edit pg_hba.conf (/etc/postgresql/16/main/ on Ubuntu and Debian, the data directory on Rocky and Alma):

# TYPE  DATABASE  USER      ADDRESS          METHOD
local   all       postgres                   peer
local   shop      +shop_rw                   scram-sha-256
host    shop      +shop_rw  127.0.0.1/32     scram-sha-256
host    shop      +shop_ro  10.8.0.0/24      scram-sha-256

The plus sign matches members of a group role. Reload with SELECT pg_reload_conf(); and test with psql -h 127.0.0.1 -U shop_app shop. Remote clients should also use hostssl lines and TLS, or come in through a tunnel as shown in remote database access.

How do you hash application passwords with pgcrypto?

Enable the pgcrypto extension and store crypt(password, gen_salt('bf', 12)), a salted bcrypt hash; check a login by comparing crypt(input, stored_hash) with the stored hash.

-- Rocky and Alma AppStream: sudo dnf install postgresql-contrib
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE app.users (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email text UNIQUE NOT NULL,
  pw_hash text NOT NULL
);
INSERT INTO app.users (email, pw_hash)
VALUES ('deploy@example.net', crypt('user-chosen-secret', gen_salt('bf', 12)));
SELECT id FROM app.users
WHERE email = 'deploy@example.net' AND pw_hash = crypt('user-chosen-secret', pw_hash);

Run the extension as the database owner so shop_rw can call its functions. Send the plain password as a bound query parameter, never pasted into SQL text, and keep log_statement off for data statements so it cannot land in logs. Many teams hash in the application with argon2 or bcrypt instead, which keeps plain passwords out of the database connection entirely; pgcrypto is the right tool when several apps share the table or the logic must live in SQL.

How do you audit and remove roles safely?

Review memberships and grants from time to time, and remove a role in three steps: hand its objects to another role, drop what it still owns or holds, then drop the role. Run the first two steps in every database where the role owns something.

\du
SELECT r.rolname, m.rolname AS member_of
FROM pg_auth_members a JOIN pg_roles r ON r.oid = a.member JOIN pg_roles m ON m.oid = a.roleid;
-- in each database:
REASSIGN OWNED BY old_dev TO shop_owner;
DROP OWNED BY old_dev;
-- then once:
DROP ROLE old_dev;

For temporary access, give the login an end date with ALTER ROLE contractor VALID UNTIL '2027-03-31';, which stops password logins after that day. When an app reports permission denied for table, check ownership with \dt app.* and rights with \dp app.orders. Roles are not part of pg_dump output, so save them as shown in back up and restore PostgreSQL.

Questions about PostgreSQL roles and permissions

What is the difference between CREATE USER and CREATE ROLE?

Only the default for LOGIN. CREATE USER adds LOGIN automatically; CREATE ROLE does not. Both make the same kind of object.

Why can my user connect but not see any tables?

It needs USAGE on the schema and SELECT on the tables, and the search path must include the schema. Check with \dn+ and \dp.

Do default privileges apply to existing tables?

No, only to objects created later by the named role. Use GRANT ... ON ALL TABLES IN SCHEMA once for the tables already there.

Should the application connect as the table owner?

Better not. The owner can drop and alter tables. Give the app a login role with DML rights only, and run migrations through a separate deploy role.

Is md5 authentication still safe to use?

It works but is weaker and deprecated in PostgreSQL 18. Re-set passwords so they are stored as SCRAM and switch pg_hba.conf lines to scram-sha-256.