Keycloak postgrest

From UVOO Tech Wiki
Revision as of 05:03, 30 August 2025 by Busk (talk | contribs) (Created page with "PostgREST can be integrated with Keycloak for authentication using JSON Web Tokens (JWTs). This setup allows Keycloak to manage user authentication and authorization, while Po...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

PostgREST can be integrated with Keycloak for authentication using JSON Web Tokens (JWTs). This setup allows Keycloak to manage user authentication and authorization, while PostgREST leverages the issued JWTs to control access to the PostgreSQL database. Key Concepts:

• JWT Secret: PostgREST requires a jwt-secret to verify the signature of incoming JWTs. This secret can be a symmetric key (HS256) or an asymmetric public key (RS256) from Keycloak. For RS256, the public key from Keycloak's realm settings (Keys tab) should be configured as a JSON Web Key (JWK) in PostgREST's jwt-secret. • Role Claim: PostgREST uses a role claim within the JWT to determine the database role under which a request should be executed. Keycloak can be configured to include a role claim in the issued JWTs, mapping user roles or attributes to database roles. The jwt-role-claim-key in PostgREST configuration specifies the JSONPath expression to extract the role from the JWT claims. • Authentication Flow:

   • A client application authenticates with Keycloak, obtaining an access token (JWT). 
   • The client sends this JWT in the Authorization header of requests to PostgREST. 
   • PostgREST verifies the JWT's signature using the configured jwt-secret. 
   • It extracts the role claim from the JWT. 
   • PostgREST then switches to the corresponding database role for the duration of the request, enforcing PostgreSQL's role-based access control.

Configuration Steps:

• Keycloak Setup:

   • Create a realm and a client in Keycloak for your PostgREST application. 
   • Configure mappers to include user roles or other relevant information in the JWT's claims, specifically mapping them to a claim that PostgREST can use as a role.

• PostgREST Configuration:

   • Set the jwt-secret in your postgrest.conf file to the appropriate Keycloak public key (as a JWK) or shared secret. 
   • Configure jwt-role-claim-key to specify where PostgREST should look for the role information within the JWT payload. For example, if Keycloak puts the role in a preferred_username claim and you want to use that as the database role, you would set jwt-role-claim-key = ".preferred_username". 
   • Ensure the corresponding database roles exist in PostgreSQL and have the necessary permissions granted.

By following these steps, Keycloak handles the identity management and token issuance, while PostgREST securely enforces access control based on the roles embedded in the JWTs.