Skip to main content

Keycloak Integration

Keycloak logo

This page provides a step-by-step guide for integrating Keycloak as a Single Sign-On (SSO) provider with the Timbr platform. By following this tutorial, you will configure OpenID Connect (OIDC) authentication with secure PKCE (Proof Key for Code Exchange), enable role mapping from Keycloak roles and groups, and allow automatic user registration on first login.

Prerequisites

Before you begin, ensure you have:

  • Keycloak server installed and running (version 12.0 or later recommended)
    • Supports self-hosted Keycloak or Red Hat Single Sign-On (RH-SSO)
  • Administrative access to your Keycloak Admin Console
  • Administrative access to the Timbr platform server to configure environment variables
  • Keycloak realm created (or use the default master realm)
  • Your Timbr domain URL (e.g., https://timbr.example.com)

Step 1: Create an OIDC Client in Keycloak

1.1 Create or Select a Realm

  1. Log in to the Keycloak Admin Console (e.g., https://keycloak.example.com/auth/admin or https://keycloak.example.com/admin for newer versions)
  2. In the top-left dropdown, select an existing realm or click Add realm to create a new one
    • Name: timbr (or your preferred name)
    • Click Create

1.2 Create a Client for Timbr

  1. In your realm, navigate to Clients in the left sidebar
  2. Click Create client (or Create in older versions)
  3. Configure the client:
SettingValue
Client typeOpenID Connect
Client IDtimbr-platform (or your preferred ID)
NameTimbr Platform
DescriptionTimbr SSO Integration
  1. Click Next

1.3 Configure Authentication Flow

On the Capability config page:

SettingValue
Client authenticationON (for confidential clients with secret)
AuthorizationOFF (unless needed)
Authentication flow
- Standard flow✅ Enabled (Authorization Code flow)
- Direct access grants❌ Disabled (not needed for web SSO)
- Implicit flow❌ Disabled
- Service accounts roles❌ Disabled

Click Next

1.4 Configure Login Settings

On the Login settings page, configure the URLs:

SettingValue
Root URLhttps://<your-timbr-domain>
Home URLhttps://<your-timbr-domain>
Valid redirect URIshttps://<your-timbr-domain>/oauth-authorized/keycloak
Valid post logout redirect URIshttps://<your-timbr-domain>/login/
Web originshttps://<your-timbr-domain> (or + to allow all redirect URI origins)

Replace <your-timbr-domain> with your actual Timbr domain.

Click Save

Redirect URI Configuration

The Valid redirect URIs must exactly match the redirect URI sent by Timbr Platform during OAuth login. Common issues:

IssueSymptomSolution
Scheme mismatchInvalid parameter: redirect_uriIf Timbr runs on HTTP (e.g., development), use http:// in Keycloak AND set OAUTH_DEFAULT_SCHEME=http
Port missingInvalid parameter: redirect_uriInclude the port if non-standard (e.g., http://localhost:8088/oauth-authorized/keycloak)
Trailing slashInvalid parameter: redirect_uriDo NOT include trailing slash in redirect URI
Wrong pathInvalid parameter: redirect_uriPath must be exactly /oauth-authorized/keycloak

Example Valid redirect URIs for different environments:

  • Production (HTTPS): https://timbr.example.com/oauth-authorized/keycloak
  • Development (HTTP): http://localhost:8088/oauth-authorized/keycloak
  • With custom port: https://timbr.example.com:8443/oauth-authorized/keycloak

Tip: You can add multiple redirect URIs (one per line) to support multiple environments.

PKCE (Proof Key for Code Exchange) provides an additional layer of security for the OAuth flow.

  1. Go to Clients → Your client → Settings tab
  2. Scroll to Advanced section (or Advanced settings)
  3. Find Proof Key for Code Exchange Code Challenge Method
  4. Set to S256 (SHA-256)

Click Save

Enhanced Security

Enabling PKCE protects against authorization code interception attacks, especially important for mobile and single-page applications.

1.6 Collect Client Credentials

After creating the client:

  1. Go to the Credentials tab
  2. Copy the Client secret – you'll use this as OAUTH_SECRET
  3. The Client ID from the Settings tab will be used as OAUTH_CLIENT_ID
  4. Note your Keycloak domain from the browser URL (e.g., https://keycloak.example.com) – you'll use this as OAUTH_BASE_URL
  5. Note your Realm name (e.g., timbr) – you'll use this as OAUTH_KEYCLOAK_REALM
Keep Credentials Secure

Store your client secret securely. Never commit it to version control or share it publicly.


Step 2: Configure Timbr Environment Variables

Add the OAuth environment variables to your timbr-platform service configuration. The configuration method depends on your deployment type:

  • Docker Compose: Add environment variables to the timbr-platform service in your docker-compose.yml file. See the Docker Compose deployment guide for the base configuration.
  • Kubernetes: Add environment variables to the timbr-platform Deployment manifest. See the Kubernetes deployment guide for the base configuration.

2.1 Required Environment Variables

# Provider identifier
OAUTH_PROVIDER=keycloak

# Client credentials from Keycloak Admin Console
OAUTH_CLIENT_ID=<your-keycloak-client-id>
OAUTH_SECRET=<your-keycloak-client-secret>

# Keycloak base URL (without /realms or /auth suffix)
# Keycloak 17+ (Quarkus): https://keycloak.example.com
# Older versions (WildFly): https://keycloak.example.com/auth
# RH-SSO: https://sso.example.com/auth
OAUTH_BASE_URL=https://<your-keycloak-domain>

# Keycloak realm name
OAUTH_KEYCLOAK_REALM=<your-realm-name>
Keycloak Version Compatibility
  • Keycloak 17+ (Quarkus-based): Uses URLs without /auth prefix (e.g., https://keycloak.example.com)
  • Older versions (WildFly-based): Use /auth prefix (e.g., https://keycloak.example.com/auth)
  • Red Hat SSO: Typically uses /auth prefix (e.g., https://sso.example.com/auth)

The integration automatically detects and handles both URL formats.

2.2 Deployment-Specific Configuration

Docker Compose

Add the OAuth environment variables to your timbr-platform service in docker-compose.yml:

services:
timbr-platform:
image: timbr/timbr-platform:latest
environment:
- OAUTH_PROVIDER=keycloak
- OAUTH_CLIENT_ID=timbr-platform
- OAUTH_SECRET=your-client-secret-here
- OAUTH_BASE_URL=https://keycloak.example.com
- OAUTH_KEYCLOAK_REALM=timbr
- AUTH_USER_REGISTRATION=true
- AUTH_USER_REGISTRATION_ROLE=viewer
- OAUTH_USE_PKCE=true
# ... other configurations

After updating your docker-compose.yml, restart the timbr-platform service:

sudo docker-compose up -d timbr-platform

Kubernetes

Add the OAuth environment variables to your timbr-platform Deployment manifest:

apiVersion: apps/v1
kind: Deployment
metadata:
name: timbr-platform
namespace: default
spec:
template:
spec:
containers:
- name: timbr-platform
image: timbr/timbr-platform:latest
env:
- name: OAUTH_PROVIDER
value: "keycloak"
- name: OAUTH_CLIENT_ID
value: "timbr-platform"
- name: OAUTH_SECRET
value: "your-client-secret-here"
- name: OAUTH_BASE_URL
value: "https://keycloak.example.com"
- name: OAUTH_KEYCLOAK_REALM
value: "timbr"
- name: AUTH_USER_REGISTRATION
value: "true"
- name: AUTH_USER_REGISTRATION_ROLE
value: "viewer"
- name: OAUTH_USE_PKCE
value: "true"
# ... other configurations

Apply the updated manifest:

kubectl apply -f timbr-platform.yaml
Using Kubernetes Secrets

For better security in Kubernetes, store sensitive values like OAUTH_CLIENT_ID and OAUTH_SECRET in Kubernetes Secrets instead of plain text in the manifest.

2.3 Optional Environment Variables

# Default scheme for OAuth redirects (default: https)
# ⚠️ IMPORTANT: Set to 'http' if your Timbr Platform runs on HTTP (e.g., development)
OAUTH_DEFAULT_SCHEME=https

# Enable user self-registration on first OAuth login
AUTH_USER_REGISTRATION=true

# Default role for self-registered users (default: viewer)
AUTH_USER_REGISTRATION_ROLE=viewer

# Allow or disable username/password login alongside OAuth
AUTH_WITH_USERPASS=true

# Custom scopes (space-separated, added to default scopes)
OAUTH_SCOPES=

# Enable PKCE (default: true)
OAUTH_USE_PKCE=true

# Enable JWT signature verification (default: true)
OAUTH_KEYCLOAK_VERIFY_SIGNATURE=true

# Enable front-channel single logout (default: false)
OAUTH_FRONT_CHANNEL_SINGLE_LOGOUT=false

# Enable Keycloak roles/groups to Timbr roles mapping (default: false)
OAUTH_ROLE_MAPPING_ENABLED=false

# JSON mapping of Keycloak roles/groups to Timbr roles
OAUTH_ROLE_MAPPING={"keycloak_admin": "admin", "keycloak_editor": "editor", "keycloak_viewer": "viewer"}

# Fallback role if no group matches (defaults to AUTH_USER_REGISTRATION_ROLE)
OAUTH_ROLE_MAPPING_DEFAULT=viewer

# Role assignment strategy: 'highest', 'all', or 'first' (default: highest)
OAUTH_ROLE_MAPPING_STRATEGY=highest

# Role priority for 'highest' strategy (comma-separated, highest first)
OAUTH_ROLE_PRIORITY=admin,editor,analyst,viewer

# Role sources to use (comma-separated): realm_roles, client_roles, groups
OAUTH_KEYCLOAK_ROLE_SOURCES=realm_roles,client_roles,groups

2.4 Example Configurations

Example 1: Basic Configuration (Keycloak 17+)

OAUTH_PROVIDER=keycloak
OAUTH_CLIENT_ID=timbr-platform
OAUTH_SECRET=abc123secret
OAUTH_BASE_URL=https://keycloak.example.com
OAUTH_KEYCLOAK_REALM=timbr
AUTH_USER_REGISTRATION=true
AUTH_USER_REGISTRATION_ROLE=viewer
OAUTH_USE_PKCE=true

Example 2: Older Keycloak / Red Hat SSO

OAUTH_PROVIDER=keycloak
OAUTH_CLIENT_ID=timbr-platform
OAUTH_SECRET=abc123secret
OAUTH_BASE_URL=https://sso.example.com/auth
OAUTH_KEYCLOAK_REALM=production
AUTH_USER_REGISTRATION=true
AUTH_USER_REGISTRATION_ROLE=viewer
OAUTH_USE_PKCE=true

Example 3: With Role Mapping

OAUTH_PROVIDER=keycloak
OAUTH_CLIENT_ID=timbr-platform
OAUTH_SECRET=abc123secret
OAUTH_BASE_URL=https://keycloak.example.com
OAUTH_KEYCLOAK_REALM=timbr
AUTH_USER_REGISTRATION=true
AUTH_USER_REGISTRATION_ROLE=viewer
OAUTH_USE_PKCE=true
OAUTH_ROLE_MAPPING_ENABLED=true
OAUTH_ROLE_MAPPING={"timbr-admin": "admin", "timbr-editor": "editor", "timbr-analyst": "analyst", "timbr-viewer": "viewer"}
OAUTH_ROLE_MAPPING_STRATEGY=highest
OAUTH_ROLE_PRIORITY=admin,editor,analyst,viewer
OAUTH_KEYCLOAK_ROLE_SOURCES=realm_roles,client_roles,groups

Step 3: Configure Keycloak Roles and Groups (Optional)

If you want to automatically assign Timbr roles based on Keycloak roles or group membership, follow these steps to configure role mapping.

3.1 Understanding Keycloak Role Architecture

Keycloak has three sources for roles that can be mapped to Timbr roles:

  1. Realm Roles (Global): Roles defined at the realm level, available to all clients
  2. Client Roles (Per-client): Roles specific to your Timbr client
  3. Groups (Hierarchical): User groups that can contain roles

You can use any combination of these sources for role mapping.

3.2 Create Realm Roles

  1. In the Keycloak Admin Console, navigate to Realm roles in the left sidebar
  2. Click Create role
  3. Configure the role:
    • Role name: Use a descriptive name (e.g., timbr-admin, timbr-analyst, timbr-viewer)
    • Description: Optional description of the role's purpose
  4. Click Save
  5. Repeat for each role you want to map (recommended: timbr-admin, timbr-editor, timbr-analyst, timbr-viewer)
Role Naming Convention

Use a consistent naming convention like timbr-<role> to make role-to-role mapping easier. The role names you create here will be used in the OAUTH_ROLE_MAPPING environment variable.

3.3 Create Client Roles (Alternative)

If you prefer client-specific roles:

  1. Navigate to Clients → Your Timbr client → Roles tab
  2. Click Create role
  3. Configure the role similar to realm roles
  4. Click Save

3.4 Create Groups (Alternative)

If you prefer using groups:

  1. Navigate to Groups in the left sidebar
  2. Click Create group
  3. Enter the group details:
    • Name: Use a descriptive name (e.g., timbr-admins, timbr-analysts, timbr-viewers)
  4. Click Create
  5. Repeat for each group you want to map

3.5 Assign Roles or Groups to Users

Assign Realm Roles:

  1. Navigate to Users → Select a user
  2. Go to the Role mapping tab
  3. Click Assign role
  4. Select the realm roles you want to assign
  5. Click Assign

Assign Client Roles:

  1. Navigate to Users → Select a user
  2. Go to the Role mapping tab
  3. Click Assign role
  4. Filter by client roles and select your Timbr client
  5. Select the client roles you want to assign
  6. Click Assign

Assign Groups:

  1. Navigate to Users → Select a user
  2. Go to the Groups tab
  3. Click Join Group
  4. Select the groups you want to add the user to
  5. Click Join

3.6 Configure Token Claims for Roles and Groups

To include roles and groups in the authentication token, configure the client scopes:

Add Realm Roles to Tokens:

  1. Go to Client scopesrolesMappers tab
  2. Find or create the realm roles mapper
  3. Ensure the following settings:
    • Mapper Type: User Realm Role
    • Token Claim Name: realm_access.roles
    • Add to ID token: ON
    • Add to access token: ON
    • Add to userinfo: ON

Add Client Roles to Tokens:

  1. Go to Client scopesrolesMappers tab
  2. Find or create the client roles mapper
  3. Ensure the following settings:
    • Mapper Type: User Client Role
    • Token Claim Name: resource_access.${client_id}.roles
    • Add to ID token: ON
    • Add to access token: ON
    • Add to userinfo: ON

Add Groups to Tokens:

  1. Go to Client scopes → Create new scope named groups (if it doesn't exist)
  2. Go to Mappers tab → Configure a new mapper
  3. Select Group Membership
  4. Configure:
    • Name: groups
    • Mapper Type: Group Membership
    • Token Claim Name: groups
    • Full group path: OFF (for simple group names)
    • Add to ID token: ON
    • Add to access token: ON
    • Add to userinfo: ON
  5. Click Save
  6. Go to Clients → Your Timbr client → Client scopes tab
  7. Add the groups scope as Default

3.7 Configure Role Mapping in Timbr

Now that your roles and groups are configured in Keycloak, map them to Timbr roles using environment variables:

# Enable role mapping
OAUTH_ROLE_MAPPING_ENABLED=true

# Map Keycloak roles/groups to Timbr roles (case-insensitive matching)
# Format: {"keycloak_role_or_group_name": "timbr_role_name", ...}
OAUTH_ROLE_MAPPING={"timbr-admin": "admin", "timbr-editor": "editor", "timbr-analyst": "analyst", "timbr-viewer": "viewer"}

# Fallback role if no mapping matches
OAUTH_ROLE_MAPPING_DEFAULT=viewer

# How to handle multiple matching roles: "first", "highest", "all"
# - first: Use the first matching role found
# - highest: Use the role with highest privileges (based on OAUTH_ROLE_PRIORITY)
# - all: Assign all matching roles to the user (additive)
OAUTH_ROLE_MAPPING_STRATEGY=highest

# Role priority for "highest" strategy (comma-separated, highest first)
OAUTH_ROLE_PRIORITY=admin,editor,analyst,viewer

# Which Keycloak sources to use for role extraction
# Options: realm_roles, client_roles, groups (comma-separated)
OAUTH_KEYCLOAK_ROLE_SOURCES=realm_roles,client_roles,groups

Example mapping strategies:

Keycloak Role/GroupTimbr RolePurpose
timbr-adminadminFull system access
timbr-editoreditorCan edit ontologies and models
timbr-analystanalystCan query and analyze data
timbr-viewerviewerRead-only access

3.8 Test Your Role Mapping

After configuring roles/groups and environment variables, test with different users:

Testing Steps:

  1. Log out of Timbr if currently logged in
  2. Click "Sign in with Keycloak"
  3. Log in with a test user who has specific roles or group membership
  4. After successful login, check the user's role in Timbr
  5. Verify the role matches your mapping configuration

Test Scenarios:

Test ScenarioUser's Keycloak Roles/GroupsExpected Timbr RoleNotes
Admin usertimbr-adminadminUser should have full system access
Editor usertimbr-editoreditorCan modify ontologies and models
Analyst usertimbr-analystanalystCan query and analyze data
Viewer usertimbr-viewerviewerRead-only access
Multi-role user (highest)timbr-analyst, timbr-vieweranalystGets higher priority role when strategy is "highest"
Multi-role user (all)timbr-editor, timbr-analysteditor, analystGets both roles when strategy is "all"
User with unmapped rolesother-roleviewerFalls back to default role
User with no roles(none)viewerFalls back to default role
Troubleshooting Role Mapping

If roles are not being assigned correctly:

  1. Verify the roles/groups are included in the ID token (check Keycloak token preview in Admin Console)
  2. Ensure role/group names in OAUTH_ROLE_MAPPING match Keycloak names (case-insensitive)
  3. Check the Timbr platform logs for role assignment messages
  4. Verify users are actually assigned the expected roles or groups in Keycloak
  5. Confirm OAUTH_ROLE_MAPPING_ENABLED=true is set
  6. Check that the appropriate client scopes (roles, groups) are assigned to your client

Step 4: Configure Front-Channel Single Logout (Optional)

Front-channel single logout allows Keycloak to send logout requests to all participating applications when a user logs out.

4.1 Enable Front-Channel Logout in Keycloak

  1. Go to Clients → Your Timbr client → Settings tab

  2. Scroll to Logout settings section

  3. Configure:

    • Front channel logout: ON
    • Front channel logout URL: https://<your-timbr-domain>/logout/
  4. Click Save

4.2 Enable in Timbr Configuration

Add to your environment variables:

# Enable front-channel single logout
OAUTH_FRONT_CHANNEL_SINGLE_LOGOUT=true

When enabled, users who log out will be redirected to Keycloak's logout endpoint, which will then redirect back to the Timbr login page after completing the logout process.


Troubleshooting

Login Redirect Issues

Symptoms:

  • Error: Invalid parameter: redirect_uri
  • User cannot complete login

Solutions:

  1. Verify redirect URI matches exactly: Check that the redirect URI in Keycloak matches what Timbr sends

    # Timbr sends: https://timbr.example.com/oauth-authorized/keycloak
    # Keycloak must have: https://timbr.example.com/oauth-authorized/keycloak
  2. Check scheme (HTTP vs HTTPS):

    • If Timbr runs on HTTP (development), set OAUTH_DEFAULT_SCHEME=http and update Keycloak redirect URI to use http://
  3. Verify port number: Include the port in both Timbr configuration and Keycloak if using non-standard ports

  4. Check for trailing slashes: Remove trailing slashes from redirect URIs

Token Validation Fails

Symptoms:

  • API returns 401 Unauthorized
  • Error message: "Invalid token" or "Token validation failed"

Solutions:

  1. Verify realm name: Ensure OAUTH_KEYCLOAK_REALM matches the actual realm name in Keycloak

  2. Check base URL format:

    • Keycloak 17+: Use https://keycloak.example.com (no /auth)
    • Older versions: Use https://keycloak.example.com/auth
  3. Verify JWT signature verification: If OAUTH_KEYCLOAK_VERIFY_SIGNATURE=true, ensure the JWKS endpoint is accessible

  4. Check token expiration: Verify the token hasn't expired

User Not Found

Symptoms:

  • Token validates successfully but user authentication fails
  • Error message: "User not found"

Solutions:

  1. Enable user registration: Set AUTH_USER_REGISTRATION=true to allow automatic user creation on first login

  2. Check user email: Verify the Keycloak user has an email address set

  3. Verify userinfo endpoint: Ensure the userinfo endpoint returns the expected user data

Role Mapping Not Working

Symptoms:

  • Users assigned wrong roles or default role instead of mapped role
  • Roles not being extracted from Keycloak

Solutions:

  1. Verify role mapping is enabled: Set OAUTH_ROLE_MAPPING_ENABLED=true

  2. Check role sources: Ensure OAUTH_KEYCLOAK_ROLE_SOURCES includes the sources you're using (realm_roles, client_roles, or groups)

  3. Verify token claims: Check that roles/groups are included in the ID token:

    • Go to Client scopes and verify mappers are configured correctly
    • Use Keycloak's token preview feature to see token contents
  4. Check role names: Ensure role names in OAUTH_ROLE_MAPPING match exactly (case-insensitive)

  5. Verify user has roles: Confirm users are assigned the expected roles or groups in Keycloak Admin Console

PKCE Errors

Symptoms:

  • Error: PKCE verification failed
  • Login fails after entering credentials

Solutions:

  1. Verify PKCE is enabled in Keycloak: Set Proof Key for Code Exchange Code Challenge Method to S256 in client settings

  2. Check PKCE configuration: Ensure OAUTH_USE_PKCE=true in Timbr configuration

  3. Session issues: Clear browser cookies and session data, then try again

Keycloak Version Compatibility

Symptoms:

  • 404 errors when accessing Keycloak endpoints
  • Unexpected URL paths

Solutions:

  1. Check Keycloak version:

    • Keycloak 17+ (Quarkus): URLs don't include /auth prefix
    • Older versions (WildFly): URLs include /auth prefix
  2. Verify base URL: Update OAUTH_BASE_URL to match your Keycloak version:

    # Keycloak 17+
    OAUTH_BASE_URL=https://keycloak.example.com

    # Older versions / RH-SSO
    OAUTH_BASE_URL=https://keycloak.example.com/auth

Security Considerations

Best Practices

  1. Use HTTPS in production: Always use HTTPS for production deployments

    • Set OAUTH_DEFAULT_SCHEME=https
    • Configure valid SSL certificates
  2. Enable PKCE: Keep OAUTH_USE_PKCE=true for enhanced security

  3. Secure client secrets:

    • Use Kubernetes Secrets or Docker Secrets for storing OAUTH_SECRET
    • Never commit secrets to version control
    • Rotate secrets periodically
  4. Enable JWT signature verification: Keep OAUTH_KEYCLOAK_VERIFY_SIGNATURE=true to validate token authenticity

  5. Use short token lifespans: Configure reasonable token expiration times in Keycloak realm settings

  6. Implement proper logout: Enable front-channel single logout for comprehensive session termination

  7. Review role mappings: Regularly audit role assignments to ensure users have appropriate access levels

  8. Monitor failed logins: Enable Keycloak's built-in security features like brute force detection

Keycloak Security Settings

In your Keycloak realm, consider enabling:

  1. Realm SettingsSecurity Defenses:

    • Brute Force Detection: Protects against password guessing attacks
    • X-Frame-Options: Prevents clickjacking
    • Content-Security-Policy: Adds additional security headers
  2. Realm SettingsTokens:

    • Set appropriate token lifespans
    • Enable token revocation
    • Configure refresh token settings
  3. Required Actions:

    • Configure user to verify email
    • Enforce password updates
    • Enable terms and conditions acceptance

Additional Resources

For additional assistance with Keycloak integration, please contact Timbr support or refer to the main Timbr documentation.