Keycloak postgrest

From UVOO Tech Wiki
Revision as of 02:32, 31 August 2025 by Busk (talk | contribs)
(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.

Test jwt

Creating a user in Keycloak and obtaining a JSON Web Token (JWT) involves several steps: 
1. Create a User in Keycloak: 

• Access the Keycloak Admin Console: Log in to your Keycloak instance's administration console (e.g., http://localhost:8080/auth/admin). 
• Select/Create a Realm: Choose an existing realm or create a new one to manage your users and clients. 
• Navigate to Users: In the left-hand menu, select "Users." 
• Add User: Click "Add user" and provide the required information, such as username, email, first name, last name, and enable the user. 
• Set Password: Go to the "Credentials" tab for the newly created user and set a password. You may also configure whether the user is required to update their password on the next login. 

2. Configure a Client for JWT Generation: 

• Navigate to Clients: In the left-hand menu, select "Clients." 
• Create a Client: Click "Create client" and provide a Client ID. 
• Configure Client Capabilities: 
    • Enable "Client authentication" and set the "Access Type" to "confidential" if you intend to use a client secret for token requests. 
    • Enable "Direct access grants" to allow users to obtain tokens directly using their username and password (though the authorization code flow is generally recommended for security). 

• Retrieve Client Secret (if applicable): If using a confidential client, go to the "Credentials" tab of the client and copy the "Client Secret." 

3. Obtain the JWT: 
The method to obtain the JWT depends on the grant type configured for your client. 

• Password Grant (for direct username/password authentication): 
    • Use a tool like curl or Postman to send a POST request to the Keycloak token endpoint (e.g., http://localhost:8080/auth/realms/<your_realm>/protocol/openid-connect/token). 
    • Include the following parameters in the request body (URL-encoded or as form data): 
        • grant_type: password 
        • client_id: Your client ID 
        • client_secret: Your client secret (if using a confidential client) 
        • username: The username of the user you created 
        • password: The password of the user you created 

    • The response will contain the access_token (your JWT), refresh_token, and other token-related information. 

    curl -X POST \
      http://localhost:8080/auth/realms/<your_realm>/protocol/openid-connect/token \
      -H 'Content-Type: application/x-www-form-urlencoded' \
      -d 'grant_type=password&client_id=<your_client_id>&client_secret=<your_client_secret>&username=<your_username>&password=<your_password>'

• Authorization Code Flow (recommended for web applications): This flow involves redirecting the user to Keycloak for authentication and then exchanging an authorization code for a token. It is more secure than the password grant. 

Note: The JWT obtained can then be used to authenticate and authorize requests to applications and services integrated with Keycloak. 



PostgREST utilizes environment variables for its configuration, offering an alternative or supplement to a configuration file. These variables are capitalized, prefixed with PGRST_, and use underscores to separate words. 
Key PostgREST Environment Variables: 

• PGRST_DB_URI: This is a crucial variable that defines the connection string to the PostgreSQL database. It follows the format: 

    postgres://user:password@host:port/database_name

This variable is essential for PostgREST to connect to and expose your database. 

• PGRST_SERVER_PORT: Specifies the port on which the PostgREST server will listen for incoming HTTP requests. 
• PGRST_JWT_SECRET: Used to define the secret key for signing and verifying JSON Web Tokens (JWTs) for authentication. 
• PGRST_DB_SCHEMAS: A comma-separated list of database schemas that PostgREST should expose through its API. 
• PGRST_DB_PRE_CONFIG: Specifies a database function that PostgREST should execute before starting to serve requests. This function can be used for in-database configuration, such as setting db-schemas or jwt-secret. 
• PGRST_APP_SETTINGS_*: Allows for configuration of custom application settings. For example, PGRST_APP_SETTINGS_MY_SETTING would correspond to app.settings.my-setting in a configuration file. 

Integration with PostgreSQL Environment Variables: 
PostgREST also supports standard libpq environment variables for constructing the database connection string, such as: 

• PGHOST: Sets the database server hostname. 
• PGPORT: Sets the TCP port number for the PostgreSQL server. 
• PGDATABASE: Sets the PostgreSQL database name. 
• PGUSER: Sets the username for connecting to the database. 
• PGPASSWORD: Sets the password for database authentication. 

Precedence of Configuration: 
PostgREST applies configuration in the following order of precedence, with later methods overriding earlier ones: 

• Config File: Values loaded from a postgrest.conf file. 
• Environment Variables: Values set via environment variables (prefixed with PGRST_). 
• In-Database Configuration: Settings defined by a db-pre-config function within the database. 

AI responses may include mistakes.