Skip to main content

PostgreSQL SSO with OIDC, RBAC, and SQL Audit Logs

Use AlmaForge, a self-hosted infrastructure access platform, to give engineers PostgreSQL access with corporate SSO, just-in-time approvals, and per-user SQL audit logs. Engineers can use psql or a GUI client. AlmaForge connects to PostgreSQL with short-lived client certificates, and the database can stay on a private network.

Setup takes four steps. Create a join token, configure PostgreSQL and the database agent, grant access through AlmaForge RBAC, and run a query.

info

Running CockroachDB? See the CockroachDB database access guide.

Prerequisites​

PostgreSQL CLI​

On your computer, check psql, the PostgreSQL command-line client:

Terminal
psql --versionpsql (PostgreSQL) 18.6 (Homebrew)

If it is missing, install libpq, which includes the client:

Terminal
brew install libpq...==> Summary...export PATH="$(brew --prefix libpq)/bin:$PATH"psql --versionpsql (PostgreSQL) 18.6 (Homebrew)

export prints nothing. Add the same export line to ~/.zshrc to keep the PATH setting in future terminals. For other operating systems, use PostgreSQL downloads.

PostgreSQL server​

On your computer, open a second terminal and SSH into the database server. Replace <ssh-user> and <database-host> with your SSH account and server address:

Terminal
ssh <ssh-user>@<database-host>...[<ssh-user>@<database-host> ~]$

On the database server, check that you can run administrator commands, then check the operating system and installed database package:

Terminal
sudo -v# No output on success. A password prompt may appear first.grep -E '^(ID_LIKE|VERSION_ID)=' /etc/os-releaseID_LIKE="rhel centos fedora"VERSION_ID="9.8"rpm -q postgresql-serverpostgresql-server-13.23-6.el9_8.x86_64

sudo -v must succeed. If PostgreSQL is not installed, install the distribution's postgresql-server package and initialize the database with postgresql-setup --initdb before continuing.

This guide uses the postgresql systemd service and /var/lib/pgsql/data directory. Packages from other repositories may use different service names and paths.

AlmaForge CLI​

On your computer, check whether alma is installed:

Terminal
alma version --clientClient Version: v2026.2.30+gc45932ada6

If the command is not found, install it and repeat the check:

Terminal
curl -fL https://get.almaforge.com/install.sh | sh...==> AlmaForge installed successfullyalma version --clientClient Version: v2026.2.30+gc45932ada6

The installer supports Linux and macOS on both amd64 and arm64. See CLI installation for package-specific options.

AlmaForge Cluster​

On your computer, sign in to your cluster and check your permissions.

Get your cluster's hostname from its administrator. If you do not have an AlmaForge cluster yet, complete the standalone deployment before continuing (or try a local Quick Start evaluation with alma demo first). Replace almaforge.example.com below with that hostname. Run the login command and complete the sign-in in your browser:

Terminal
alma login --proxy=almaforge.example.com:443
text
...
> Profile URL: https://almaforge.example.com:443
Logged in as: alice@example.com
Cluster: almaforge.example.com
Roles: admin
...

After signing in, check your account and roles:

Terminal
alma status
text
> Profile URL: https://almaforge.example.com:443
Logged in as: alice@example.com
Cluster: almaforge.example.com
Roles: admin
...

In the status output, check that:

  • Cluster names the cluster you intend to configure.
  • Logged in as shows your account.
  • Roles includes admin.

If admin is missing, ask a cluster administrator to grant that role, then run alma logout and repeat the login and status commands. Continue once Roles includes admin.

Step 1. Create AlmaForge join token​

On your computer, create an AlmaForge join token. The database agent uses it to join your AlmaForge cluster:

Terminal
alma create token --services=databaseToken created.  client_id:     <client-id>  client_secret: <client-secret>

You will copy client_id and client_secret into the agent configuration in Step 2. They are valid for 30 minutes. If they expire before the agent joins, create a new token and use its values.

Step 2. Configure the PostgreSQL server​

Install and configure the agent​

The agent is almad with its Database Service enabled. It connects outward to your cluster on port 443 and carries connections between users and PostgreSQL.

On the PostgreSQL server, check whether almad is installed:

Terminal
almad versionAlmaForge v2026.2.30+gc45932ada6

If the command is not found, install the AlmaForge package:

Terminal
curl -fL https://get.almaforge.com/install.sh | sh...==> AlmaForge installed successfullyalmad versionAlmaForge v2026.2.30+gc45932ada6

On an RPM-based system, the installer uses the RPM package and installs the almad systemd service. It supports both amd64 and arm64. The version command must succeed before you configure the agent. For other Linux distributions, see Linux package installation.

Already running an agent on this host?

Keep its existing settings and enable ALMA_DATABASE_SERVICE=true. Preserve the other services and label selectors. The join credentials must permit the database service. The local target created below does not need a label selector.

On the PostgreSQL server, open the agent configuration:

Terminal
sudoedit /etc/almaforge/almad.env# Your text editor opens.

For a new agent, enter the settings below. Replace ALMA_PROXY with your cluster's hostname and port 443. Set ALMA_CLIENT_ID and ALMA_CLIENT_SECRET to the values from Step 1:

almad.env:

/etc/almaforge/almad.env
# Database Service agent on the PostgreSQL host.
# Install at /etc/almaforge/almad.env as root:root with mode 0600.
ALMA_PROXY=almaforge.example.com:443

# Printed by `alma create token --services=database`.
ALMA_CLIENT_ID=paste-client-id-here
ALMA_CLIENT_SECRET=paste-client-secret-here

ALMA_DATABASE_SERVICE=true
ALMA_SSH_SERVICE=false

# Agent labels, separate from the database's labels.
ALMA_LABELS=env=demo

Save the file and close the editor. Restrict it to root because it contains the join credentials:

Terminal
sudo chown root:root /etc/almaforge/almad.env# No output on success.sudo chmod 0600 /etc/almaforge/almad.env# No output on success.

Create the TLS certificates​

The agent and PostgreSQL run on the same server. Their connection uses the loopback interface (localhost, or 127.0.0.1), so this traffic stays on that server. A self-signed certificate for localhost is sufficient. You do not need a public hostname or a certificate from a public CA.

PostgreSQL uses the AlmaForge database CA to verify client certificates presented by the agent.

Keep running these commands on the PostgreSQL server.

Download your cluster's public database CA. Replace almaforge.example.com with your cluster's hostname:

Terminal
curl -fsS -o almaforge-db-ca.pem 'https://almaforge.example.com:443/api/v1/auth/export?type=db'# No output on success.openssl x509 -in almaforge-db-ca.pem -noout# No output means the file contains a valid certificate.sudo install -o postgres -g postgres -m 0644 almaforge-db-ca.pem /var/lib/pgsql/data/server.cas# No output on success.

Create a self-signed server certificate and private key for localhost:

Terminal
sudo openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \    -subj '/CN=localhost' \    -addext 'subjectAltName=DNS:localhost,IP:127.0.0.1' \    -keyout /var/lib/pgsql/data/server.key -out /var/lib/pgsql/data/server.crt...-----sudo chown postgres:postgres /var/lib/pgsql/data/server.key /var/lib/pgsql/data/server.crt# No output on success.sudo chmod 0600 /var/lib/pgsql/data/server.key# No output on success.

Enable TLS in PostgreSQL​

Open the PostgreSQL configuration on the server:

Terminal
sudoedit /var/lib/pgsql/data/postgresql.conf# Your text editor opens.

Configure PostgreSQL to require TLS and use the certificate files:

postgresql.conf:

/var/lib/pgsql/data/postgresql.conf
# Local TLS configuration on a dedicated PostgreSQL host.
# Configures mutual TLS using the local server certificate and AlmaForge database CA.
listen_addresses = 'localhost'
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
ssl_ca_file = 'server.cas'

Open pg_hba.conf and require client certificates for local TCP connections:

Terminal
sudoedit /var/lib/pgsql/data/pg_hba.conf# Your text editor opens.

Replace any existing password or ident rules for 127.0.0.1/32 and ::1/128 with the hostssl ... cert rules below. PostgreSQL uses the first matching rule, so put these rules above any broader rule that also matches loopback connections. Keep a local rule for the postgres user's Unix-socket connection.

pg_hba.conf:

/var/lib/pgsql/data/pg_hba.conf
# Local TLS configuration on a dedicated PostgreSQL host.
# Local root and postgres connect over the socket. TCP connections require client certificates.
local all all peer
hostssl all all 127.0.0.1/32 cert
hostssl all all ::1/128 cert

Save the file and restart PostgreSQL:

Terminal
sudo systemctl restart postgresql# No output on success.systemctl is-active postgresqlactive

Create the database and accounts​

From /tmp, run psql as the postgres user over the local socket to create the demo database, the administrative account for automatic user provisioning, the user role, and the sample table. If you run the command from a home directory with mode 0700, sudo -u postgres psql can print the harmless warning could not change directory ... Permission denied.

Terminal
cd /tmp# No output on success.sudo -u postgres psql -v ON_ERROR_STOP=1 <<'EOF'SELECT 'CREATE DATABASE demo' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'demo')\gexecSELECT 'CREATE ROLE "alma-admin" LOGIN CREATEROLE' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'alma-admin')\gexecSELECT 'CREATE ROLE "alma-auto-user"' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'alma-auto-user')\gexecSELECT 'CREATE ROLE "alma-demo-reader"' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'alma-demo-reader')\gexecGRANT "alma-auto-user" TO "alma-admin" WITH ADMIN OPTION;GRANT "alma-demo-reader" TO "alma-admin" WITH ADMIN OPTION;\c demoREVOKE CREATE ON SCHEMA public FROM PUBLIC;GRANT USAGE, CREATE ON SCHEMA public TO "alma-admin";CREATE TABLE IF NOT EXISTS demo (id INT PRIMARY KEY, name TEXT);INSERT INTO demo VALUES (1, 'alice'), (2, 'bob'), (3, 'carol') ON CONFLICT DO NOTHING;GRANT USAGE ON SCHEMA public TO "alma-demo-reader";GRANT SELECT ON ALL TABLES IN SCHEMA public TO "alma-demo-reader";EOF

Register PostgreSQL with the agent​

Still on the PostgreSQL server, display the public server certificate:

Terminal
sudo cat /var/lib/pgsql/data/server.crt-----BEGIN CERTIFICATE-----...-----END CERTIFICATE-----

Copy the entire certificate, including the BEGIN and END lines. The agent uses it to verify PostgreSQL. Then open the DatabaseTarget configuration:

Terminal
sudo install -d -o root -g root -m 0700 /etc/almaforge/almad.d# No output on success.sudoedit /etc/almaforge/almad.d/postgres.yaml# Your text editor opens.

For a new file, copy the following YAML. If the file already exists, update the existing resource and preserve its other settings. Replace <paste the complete server certificate here> with the certificate you copied. Indent every certificate line by six spaces beneath caCert: |:

target.yaml.in:

/etc/almaforge/almad.d/postgres.yaml
# PostgreSQL target for an agent running on the database server.
# Replace caCert with the complete server certificate or its issuing CA.
apiVersion: almaforge.com/v1
kind: DatabaseTarget
metadata:
name: postgres
labels:
db: postgresql
env: prod
spec:
protocol: postgres
uri: 127.0.0.1:5432
adminUser:
name: alma-admin
defaultDatabase: demo
tls:
caCert: |
<paste the complete server certificate here>

Check that the certificate includes both its BEGIN and END lines, then save the file and close the editor. Restrict the file to root:

Terminal
sudo chown root:root /etc/almaforge/almad.d/postgres.yaml# No output on success.sudo chmod 0600 /etc/almaforge/almad.d/postgres.yaml# No output on success.

Start and check the agent​

Enable the services at boot and start the agent:

Terminal
sudo systemctl enable postgresql almad...sudo systemctl restart almad# No output on success.systemctl is-active postgresql almadactiveactive

Both services must report active. If either fails, inspect its log:

Terminal
sudo journalctl -u postgresql -u almad -n 50 --no-pager...<date> <time> <database-host> almad[<pid>]: <log-message>...

Resolve any reported errors before continuing. The agent reads the target configuration at startup, so restart almad after changing /etc/almaforge/almad.d/postgres.yaml.

Step 3. Grant access​

On your computer, confirm that the agent has registered the database:

Terminal
alma get dbHost             Name            Protocol       URI                 Labels             Version---------------- --------------- -------------- ------------------- ------------------ --------<database-host>  postgres        postgres       <database-uri>      db=postgresql ... 2026.2.30

Check that postgres appears with protocol postgres and your database server in the Host column. If either is missing, see Database is missing or has no host.

Download postgres-access.yaml and save it locally. This role allows access to targets labeled db: postgresql and to the demo database. createDbUserMode: keep creates a database account named after the user's full AlmaForge login, such as alice@example.com, and retains it after the session ends. PostgreSQL grants control what the account can do inside the database. The alma-demo-reader role permits reading the sample table.

examples/databases/postgresql/roles/postgres-access.yaml
# Allow access to the dedicated PostgreSQL target.
# Map an SSO group to this role in your OIDC connector.
apiVersion: almaforge.com/v1
kind: Role
metadata:
name: postgresql-access
spec:
options:
createDbUserMode: keep # Create an account for the AlmaForge login and retain it after disconnect.
allow:
databaseLabels:
db: postgresql
databaseRoles:
- alma-demo-reader
databaseNames:
- demo

Apply the role:

Terminal
alma apply -f postgres-access.yamlrole 'postgresql-access' has been created

Creating the role does not assign it to anyone. To grant it to an SSO group, list your connectors:

Terminal
alma get oidcKind          Name------------- -----------OIDCConnector company-sso

Find the connector your team uses to sign in. Replace <connector-name> with its name from the output, then open it in your text editor:

Terminal
alma edit oidc/<connector-name># Your text editor opens. After saving your changes:oidc connector "<connector-name>" has been updated

Under spec.claimsToRoles, find the entry for the group that should have PostgreSQL access. Add postgresql-access to that entry's roles list. Preserve the existing roles and mappings, including those that grant admin, then save and close the editor. The command applies your changes. If the group has no mapping yet, follow OIDC role mapping to add one, or check Identity provider group mapping below for Okta, Microsoft Entra ID, and Google Workspace group formats.

Step 4. Connect​

On your computer, sign out of saved sessions, then sign back in with an account in the group granted access in Step 3. logout clears saved sessions for all clusters. Use your cluster's hostname in the login command.

If you're switching accounts, open the sign-in link in a private browser window or select a different account when your identity provider prompts you. Otherwise, the browser may reuse your previous sign-in.

Terminal
alma logoutLogged out all users from all proxies.alma login --proxy=almaforge.example.com:443...> Profile URL:        https://almaforge.example.com:443  Logged in as:       alice@example.com  Cluster:            almaforge.example.com  Roles:              postgresql-access  ...alma status> Profile URL:        https://almaforge.example.com:443  Logged in as:       alice@example.com  Cluster:            almaforge.example.com  Roles:              postgresql-access  ...

Check that Roles includes postgresql-access. If it is missing, check your SSO group membership and the mapping from Step 3 before continuing.

Connect to the sample database with alma exec and psql as shown below. For DataGrip, DBeaver, or pgAdmin, follow GUI clients and scripts to open a local connection.

Terminal
alma exec db/postgres --db-name=demo...demo=> SELECT current_user, current_database();   current_user    | current_database-------------------+------------------ alice@example.com | demo(1 row)
demo=> SELECT count(*) FROM demo; count------- 3(1 row)

The first query must show your full AlmaForge login and database demo. The second must return 3. These results confirm that account creation, certificate authentication, and access to the sample data work. Type \q to exit.

Optional audit log verification​

In AlmaForge, the SQL audit log records the engineer's SSO identity even when several engineers use the same PostgreSQL role. Run the audit command with an admin or auditor account. If you're signed in as the test user, switch accounts using the browser sign-in guidance in Step 4.

Terminal
alma logoutLogged out all users from all proxies.alma login --proxy=almaforge.example.com:443...alma status...  Roles:              admin  ...alma audit --last=1h --type=DatabaseSessionQuery --limit=1 -o json

audit-event.json:

examples/databases/postgresql/audit-event.json
[
{
"apiVersion": "almaforge.com/v1",
"kind": "AuditEvent",
"spec": {
"id": "da455e0f-c27d-459f-a218-4e83b3db9426",
"type": "DatabaseSessionQuery",
"code": "TDB02I",
"verb": "execute",
"outcome": "success",
"index": 2,
"timestamp": "2026-05-18T22:24:11.503000Z",
"clusterName": "almaforge.example.com",
"actor": {
"name": "alice@example.com",
"type": "user"
},
"session": {
"id": "1cdcd17c-9d9f-4806-9a3c-dffe3f873b0c"
},
"status": {
"success": true
},
"database": {
"service": "postgres",
"protocol": "postgres",
"uri": "127.0.0.1:5432",
"name": "demo",
"user": "alice@example.com",
"roles": ["alma-demo-reader"],
"type": "self-hosted",
"origin": "config-file"
},
"databaseSessionQuery": {
"dbQuery": "SELECT count(*) FROM demo;"
}
}
}
]

In this event, spec.actor.name identifies the engineer and spec.databaseSessionQuery.dbQuery contains the SQL. The database login is alice@example.com in spec.database.user, and the role granted for the session is alma-demo-reader in spec.database.roles. PostgreSQL's log_line_prefix setting (%u) identifies the database session user in local logs, including pgAudit output.

DatabaseSessionQuery carries the simple text statements that psql sends in this example. Clients that use prepared statements, such as DBeaver, DataGrip, or pgAdmin, record prepared statements across PostgresParse (query text), PostgresBind (parameters), and PostgresExecute instead. A DatabaseSessionQuery filter does not return those events. Repeat --type for each event type you want, or omit the flag to list every event in the window:

Terminal
alma audit --last=1h \  --type=DatabaseSessionQuery --type=PostgresParse \  --type=PostgresBind --type=PostgresExecute

See Audit events for the full event list and the storage guide to export AuditEvent streams to S3 or a SIEM.

Identity provider group mapping​

Each OIDCConnector resource maps identity provider groups to AlmaForge roles under spec.claimsToRoles. Group delivery differs across providers:

Identity providerValue to match in spec.claimsToRolesWhere the value comes from
OktaExact group nameThe groups claim, preferably from a custom authorization server.
Microsoft Entra ID (Azure AD)Security group's Object IDThe app registration's groups claim. For users with more than 200 groups, configure the app to emit assigned groups.
Google WorkspaceGroup's primary email addressThe Cloud Identity Groups API, accessed through a service account with domain-wide delegation.
Generic OIDCExact value in the configured group claimThe identity provider's ID token. Applies to Keycloak, Authentik, Auth0, Zitadel, and Dex.

Google Workspace ID tokens omit group memberships. AlmaForge looks up Google Groups through the Cloud Identity Groups API.

Advanced configuration​

Automatic user provisioning​

The example enables createDbUserMode: keep. The agent connects as alma-admin, creates an account named after the user's full AlmaForge login, and grants alma-demo-reader for the session. It does not provision an arbitrary name supplied through --user. The account remains after disconnect. Use bestEffortDrop to request its removal instead.

If you prefer not to create per-engineer roles in pg_roles, you can omit automatic user provisioning and map an AlmaForge role to a pre-existing shared PostgreSQL role (such as a read-only role). In both models, spec.actor.name in the AlmaForge audit log records which SSO user ran each query. See automatic user provisioning for role settings and cleanup behavior. Removing an engineer from the identity provider blocks their next AlmaForge login. A cluster lock can terminate active sessions.

Standing read-only access with just-in-time read-write elevation​

PostgreSQL's built-in CREATE ROLE ... VALID UNTIL clause sets an expiration timestamp only for password authentication. PostgreSQL does not enforce VALID UNTIL on certificate-authenticated logins and does not close sessions that are already open.

To enforce time-bounded elevation, keep postgresql-access mapped to your SSO group for routine SELECT queries through alma-demo-reader. Put write or schema administration privileges in a separate AlmaForge role, such as postgresql-rw, with a short maxSessionTTL. Engineers can request that role when they need elevated access.

Allow the baseline role to request postgresql-rw, then designate a reviewer role as shown in Just-in-Time Access or enable PagerDuty on-call auto-approval. When an engineer needs write access, they submit an access request:

Terminal
alma request create \  --roles=postgresql-rw \  --reason="incident-42: backfill missing order rows"

A reviewer inspects and approves the request from the CLI or Web UI:

Terminal
alma request ls --reviewablealma request review <request-id> --approve --reason="approved for incident-42"

After approval, close any open PostgreSQL sessions for that user so the agent can update their granted database roles, then assume the request and reconnect until the elevated certificate's TTL expires. You can also pass --wait to request create to wait for a review:

Terminal
alma request assume <request-id>alma exec db/postgres --db-name=demo

Set disconnectExpiredCert: true on the elevated role to terminate open database sessions automatically when the window closes.

Dynamic labels​

Use spec.dynamicLabels for values that a command on the agent refreshes, such as the PostgreSQL version. The command must be available on that host.

postgres-dynamic-labels.yaml:

examples/databases/postgresql/kinds/postgres-dynamic-labels.yaml
# Self-hosted PostgreSQL with dynamic labels. Each entry under
# `spec.dynamicLabels` runs a shell command on the agent at the
# configured period and stores stdout as the label value. Use this
# for values that change between deployments — engine version,
# replica role, pgBouncer pool name — instead of hard-coding them
# under `metadata.labels`.
apiVersion: almaforge.com/v1
kind: DatabaseTarget
metadata:
name: orders-postgres
labels:
env: prod
team: payments
spec:
protocol: postgres
uri: orders-prod.internal:5432
dynamicLabels:
engine_version:
period: 5m # Refresh every five minutes.
command: # Argv form; the agent runs the binary directly, no shell parsing.
- /bin/sh
- -c
- psql --version | awk '{print $3}'

Multiple PostgreSQL instances per agent​

Add a target file per database under /etc/almaforge/almad.d/ and restart the agent. For centrally applied targets, configure ALMA_MATCH_LABELS to match their labels. The agent must reach each target's address, and the server certificates must cover those addresses.

Identity files for non-interactive psql​

For unattended jobs, use workload identity and grant only the database names and roles the job needs.

GUI clients and scripts​

For a GUI client such as DataGrip, DBeaver, or pgAdmin, or for local scripts, leave alma port-forward running:

Terminal
alma port-forward db/postgres --db-name=demoForwarding from 127.0.0.1:5432 -> 5432...

Use the address and port it prints, your full AlmaForge login as the user, and demo as the database. Use plain TCP (sslmode=disable if the client defaults to TLS) to the local listener on 127.0.0.1. Leave the password field blank and remove matching ~/.pgpass or PGPASSWORD entries so the client does not send stale credentials. AlmaForge authenticates the session over mTLS through the encrypted tunnel.

Architecture​

The AlmaForge database agent reaches PostgreSQL on localhost or a private interface and opens an outbound TLS tunnel to your self-hosted proxy on port 443. Engineers sign in through your OIDC provider and connect through AlmaForge. The proxy and SQL traffic stay on your infrastructure.

PostgreSQL verifies the agent's short-lived client certificate against your cluster's database CA. The agent verifies the PostgreSQL server certificate against spec.tls.caCert and sends SQL audit events to the cluster. See the database architecture for the Auth, Proxy, and Database Service roles.

PostgreSQL database access topology

Troubleshooting​

Database is missing or has no host​

On the database server, check that /etc/almaforge/almad.d/postgres.yaml exists and ALMA_DATABASE_SERVICE=true is set in /etc/almaforge/almad.env. The agent must reach your cluster on port 443. If the agent logs connection refused when dialing PostgreSQL, verify that PostgreSQL is active and listening on 127.0.0.1:5432 (or the target URI in postgres.yaml). Inspect the service logs:

Terminal
sudo journalctl -u almad -n 50 --no-pager...<date> <time> <database-host> almad[<pid>]: <log-message>...

Restart almad after correcting its configuration, then repeat alma get db on your computer.

Access is denied​

Run alma status and check for postgresql-access:

  • Role missing after login: Verify the SSO group mapping from Step 3. Confirm that Okta uses the exact group name, Microsoft Entra ID uses the group's Object ID UUID rather than its display name, and Google Workspace uses the group's primary email address with Cloud Identity API delegation configured. Then run alma logout and alma login.
  • Database or table denied: Check that the role's database labels match postgres.yaml, --db-name matches an allowed database name, and the PostgreSQL role (alma-demo-reader) has USAGE on the schema and SELECT on the target tables.
  • Session disconnects when certificate expires: Your role or just-in-time request reached maxSessionTTL, and the role sets disconnectExpiredCert: true. Run alma login or submit a new access request to obtain a fresh certificate.
  • Denied with lock in force: An administrator placed a cluster lock on your user, role, or target. Ask a cluster administrator to review active locks.
  • Agent join token rejected: Create a fresh database token with alma create token --services=database (valid for 30 minutes) and update ALMA_CLIENT_ID and ALMA_CLIENT_SECRET in /etc/almaforge/almad.env.

Account creation fails​

Check that the target file has adminUser.name: alma-admin and adminUser.defaultDatabase: demo, and that your role has createDbUserMode: keep. The alma-admin account must have LOGIN, CREATEROLE, permission to install its procedures, and WITH ADMIN OPTION permission to grant alma-auto-user and alma-demo-reader (required on PostgreSQL 16 and later). Connect with your own AlmaForge login, which the CLI selects automatically. See automatic user provisioning.

PostgreSQL rejects the certificate login​

For no pg_hba.conf entry, Ident authentication failed, or a password prompt from PostgreSQL, check /var/lib/pgsql/data/pg_hba.conf. The setup uses hostssl ... cert for both localhost addresses (127.0.0.1/32 and ::1/128). PostgreSQL uses the first matching rule, so an earlier ident, scram-sha-256, or md5 rule on localhost changes how the connection authenticates. Keep the local all all peer rule for maintenance over the Unix socket, and restart PostgreSQL after editing pg_hba.conf.

Certificate validation fails​

PostgreSQL's ssl_ca_file must reference server.cas, the public AlmaForge database CA downloaded from the cluster. The agent's spec.tls.caCert must contain the PostgreSQL server certificate, and that certificate must be within its validity dates and include the target host or IP in subjectAltName. These files establish trust in opposite directions. If you rotate the server certificate, update /etc/almaforge/almad.d/postgres.yaml and restart almad.

Self-hosted PostgreSQL access options compared​

With AlmaForge, engineers sign in through OIDC and the database agent connects to PostgreSQL over mutual TLS (mTLS) using short-lived client certificates. This can replace shared passwords in .pgpass files and PGPASSWORD variables.

ApproachHow users authenticateHow SQL activity identifies users
Shared PostgreSQL loginShared database passwordPostgreSQL logs show the shared database role.
PostgreSQL LDAP or PAMPassword checked through LDAP or PAMPostgreSQL logs show the database role, which must already exist.
PostgreSQL 18 native OAuthOAuth token checked by a server-side validatorPostgreSQL logs show the database role.
Vault dynamic database credentialsPassword issued per leaseCorrelate the Vault lease with PostgreSQL logs.
AlmaForgeOIDC sign-in and short-lived client certificatesThe cluster audit event records the SSO user alongside the database role.

For temporary write access, use an approval-gated access request. AlmaForge can close open PostgreSQL sessions when the elevated certificate expires. The proxy and SQL traffic stay on your infrastructure.

Frequently asked questions​

Does PostgreSQL support Okta, Entra ID, Google Workspace, or Keycloak SSO natively?​

PostgreSQL 18 introduced native OAuth 2.0 authentication compatible with OIDC providers. To use it, configure a validator for your provider's tokens, map identities to PostgreSQL roles, and use a client that supports OAuth. AlmaForge handles SSO for your existing PostgreSQL clients and adds automatic user provisioning, just-in-time approvals, and per-user SQL audit logs across supported databases.

Can you use the same corporate SSO for self-hosted PostgreSQL, AWS RDS, Google Cloud SQL, and Azure Database for PostgreSQL?​

Yes. Engineers can sign in to AlmaForge with the same corporate SSO for self-hosted PostgreSQL and supported managed databases, including Amazon RDS, Google Cloud SQL, and Azure Database for PostgreSQL. Configure the database connection using each service's authentication settings.

How do you replace shared PostgreSQL passwords and .pgpass files with corporate SSO?​

Use AlmaForge to sign engineers in through your identity provider and connect them to PostgreSQL with short-lived client certificates. In Step 2, configure hostssl ... cert in pg_hba.conf for the agent connection. After verifying access, remove the old .pgpass entries and PGPASSWORD settings for that connection.

How do Okta, Microsoft Entra ID (Azure AD), and Google Workspace groups map to PostgreSQL roles?​

In AlmaForge, the OIDC connector tells the cluster which access role to grant when an engineer signs in. In spec.claimsToRoles, use the Okta group name, the Entra ID security group's Object ID, or the Google group's primary email address. See Identity provider group mapping for how each provider supplies that value.

Why use a self-hosted database access proxy instead of PostgreSQL LDAP authentication or HashiCorp Vault dynamic credentials?​

Use AlmaForge when engineers need corporate SSO, approval before gaining write access, and an audit log that names the person who ran a query. LDAP validates a password, and Vault issues a temporary database password. With AlmaForge, the agent connects using a short-lived certificate and records the engineer's SSO identity. See PostgreSQL access options compared.

How do developers connect to private PostgreSQL databases without a VPN or SSH bastion?​

Engineers sign in to your self-hosted AlmaForge proxy, then connect with psql or a GUI client. The database agent opens an outbound TLS tunnel to the proxy on port 443, so PostgreSQL can stay on a private network without a public database port, VPN, or SSH bastion. See Architecture.

How do you grant just-in-time read-write access to production PostgreSQL?​

Use AlmaForge to give engineers read-only PostgreSQL access by default. When they need to write, they request a separate role. After approval, they activate it and reconnect with a short-lived certificate. Follow Set up just-in-time read-write access and see maxSessionTTL and disconnectExpiredCert in the Role reference for certificate expiry and session cutoff.

How do you audit PostgreSQL queries by SSO identity when engineers share a database role?​

In the AlmaForge SQL audit log, spec.actor.name identifies the engineer even when several people use the same PostgreSQL login. Read spec.database.user for the database login and spec.database.roles for roles granted when the agent provisions a user. See Verify the SQL audit log for a sample event.

How do you automate PostgreSQL user provisioning and offboarding through corporate SSO?​

Enable automatic user provisioning so AlmaForge creates a PostgreSQL account from the engineer's SSO login on first connection and grants the database roles you configured. Remove the engineer from your identity provider to block their next AlmaForge sign-in. Apply a cluster lock to end active sessions immediately.

How do you connect DataGrip, DBeaver, or pgAdmin to PostgreSQL using corporate SSO?​

Sign in to AlmaForge and run alma port-forward db/postgres --db-name=demo. Point your GUI client at the local address and port the command prints. Use your full AlmaForge login as the database username and leave the password blank. Follow GUI clients and scripts for the connection settings.

How do you enable corporate OIDC SSO for PostgreSQL running in Docker or Kubernetes?​

Run the AlmaForge database agent where it can reach PostgreSQL. For Docker, follow the container environment-file example and replace ALMA_SSH_SERVICE=true with ALMA_DATABASE_SERVICE=true. For Kubernetes, use the agent Helm chart. Follow Step 2 for PostgreSQL TLS settings and use a server certificate that covers the address the agent uses.

References​