Setting up Keycloak 26 for OIDC token flows and production
Run Keycloak 26.8.2 in Docker, verify PKCE and client credentials tokens with JWKS, configure Audience mappers, and switch to production behind a reverse proxy.
Moving a local Keycloak 26 container to production usually breaks in four places: bootstrap admin initialization, missing
audclaims, skipped--import-realmupdates, and reverse-proxy hostname mismatches. This guide walks through each setting with verified requests and outputs fromquay.io/keycloak/keycloak:26.8.2and PostgreSQL 16.
Every log snippet and token payload below comes from live HTTP, OIDC, and Admin REST API calls against local
quay.io/keycloak/keycloak:26.8.2andpostgres:16-alpinecontainers. Examples use port8080andexample.testfor easy local reproduction.
When to use Keycloak and starting locally
Keycloak makes sense when multiple web apps and APIs need one central identity provider (IdP). It gives you OIDC, OAuth 2.0, SAML 2.0, PKCE enforcement, service accounts for machine-to-machine (M2M) calls, and role mapping out of the box.
That doesn’t mean every project needs it. If you run a single backend app with no plans for cross-app SSO, built-in framework sessions or a managed auth provider will cost less operational effort. For a small homelab protecting a handful of self-hosted apps, a lightweight IdP uses far less memory—I documented that setup in my Outline Wiki and Authelia OIDC guide.
Bootstrap admin variables and start-dev vs start
The first change you’ll notice in Keycloak 26 is how the initial admin account is created. Old tutorials still reference KEYCLOAK_ADMIN and KEYCLOAK_ADMIN_PASSWORD, which are now deprecated. In 26.8.2, those variables still work but log deprecation warnings on startup:
1
2
3
WARN [org.keycloak.services] (main) KC-SERVICES0110: Environment variable 'KEYCLOAK_ADMIN' is deprecated, use 'KC_BOOTSTRAP_ADMIN_USERNAME' instead
WARN [org.keycloak.services] (main) KC-SERVICES0110: Environment variable 'KEYCLOAK_ADMIN_PASSWORD' is deprecated, use 'KC_BOOTSTRAP_ADMIN_PASSWORD' instead
INFO [org.keycloak.services] (main) KC-SERVICES0077: Created temporary admin user with username legacyadmin
Use KC_BOOTSTRAP_ADMIN_USERNAME and KC_BOOTSTRAP_ADMIN_PASSWORD instead:
1
2
3
4
5
6
docker run -d --name keycloak-dev \
-p 8080:8080 \
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
-e KC_BOOTSTRAP_ADMIN_PASSWORD=change-me-local \
quay.io/keycloak/keycloak:26.8.2 \
start-dev
Keycloak logs KC-SERVICES0077: Created temporary admin user with username admin and flags the user in the Admin REST API (/admin/realms/master/users?username=admin&exact=true):
1
2
3
4
5
6
7
{
"username": "admin",
"enabled": true,
"attributes": {
"is_temporary_admin": ["true"]
}
}
These bootstrap variables only run once, when the master realm initializes an empty database. When I restarted the container against the same PostgreSQL volume with KC_BOOTSTRAP_ADMIN_USERNAME=admin2, logging in as admin2 failed with HTTP 400 invalid_grant while the original admin account kept working. Before going live, sign in with the temporary admin, create a permanent admin user in master, and delete the temporary one.
You also need to separate start-dev from start early:
| Setting | start-dev (development) | start (production) |
|---|---|---|
| Default database | Embedded H2 (jdbc-h2, lost on container removal) | External RDBMS required (explicitly set KC_DB) |
| HTTP / TLS | Allows HTTP 8080 (Profile dev activated) | Requires HTTPS; exits if TLS keys are missing |
| Hostname checks | Relaxed (hostname-strict=false) | Strict (KC_HOSTNAME required) |
| Production use | Not for production (DO NOT use this configuration in production) | Standard production command |
Running quay.io/keycloak/keycloak:26.8.2 start without TLS certificates or KC_HTTP_ENABLED=true immediately fails with exit code 2:
1
2
WARNING: Usage of the default value for the db option in the production profile is deprecated. Please explicitly set the db instead.
Key material not provided to setup HTTPS. Please configure your keys/certificates, or if HTTPS access is not needed see the `http-enabled` option. If you meant to start the server in development mode, see the `start-dev` command.
Realm, Client, Role hierarchy and JSON import
Treat the built-in master realm strictly as the server administration plane. Putting application users and clients inside master mixes server-admin privileges with app-level auth. Creating a dedicated realm such as demo-realm isolates everything starting from the OIDC Discovery document (/.well-known/openid-configuration).
flowchart TD
R["Realm (demo-realm)"] --> C["Client (demo-spa / demo-worker)"]
R --> U["User / Service Account"]
R --> RR["Realm Role (app-user)"]
C --> CR["Client Role (order:read)"]
C --> CS["Client Scope (Audience mapper)"]
CS --> T["JWT Access / ID Token"]
Comparing GET /realms/demo-realm/.well-known/openid-configuration against master confirms that all six core endpoints (issuer, authorization_endpoint, token_endpoint, jwks_uri, userinfo_endpoint, and end_session_endpoint) are scoped cleanly under /realms/<realm>/...:
1
2
3
4
5
6
7
8
{
"issuer": "http://localhost:8080/realms/demo-realm",
"authorization_endpoint": "http://localhost:8080/realms/demo-realm/protocol/openid-connect/auth",
"token_endpoint": "http://localhost:8080/realms/demo-realm/protocol/openid-connect/token",
"jwks_uri": "http://localhost:8080/realms/demo-realm/protocol/openid-connect/certs",
"userinfo_endpoint": "http://localhost:8080/realms/demo-realm/protocol/openid-connect/userinfo",
"end_session_endpoint": "http://localhost:8080/realms/demo-realm/protocol/openid-connect/logout"
}
Reproducible setup with --import-realm and the restart trap
To recreate a realm in local development or CI without clicking through the Admin Console, mount your realm JSON at /opt/keycloak/data/import/demo-realm-realm.json and pass --import-realm:
1
2
3
4
5
6
7
docker run -d --name keycloak-import \
-p 8080:8080 \
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
-e KC_BOOTSTRAP_ADMIN_PASSWORD=change-me-local \
-v "$(pwd)/demo-realm-realm.json:/opt/keycloak/data/import/demo-realm-realm.json:ro" \
quay.io/keycloak/keycloak:26.8.2 \
start-dev --import-realm
On an empty PostgreSQL database, Keycloak imports demo-realm using the IGNORE_EXISTING strategy. However, if you edit displayName in the JSON file and restart the container against the same database, Keycloak skips the file and keeps the existing database state:
1
2
3
4
5
6
7
# First boot (empty database)
INFO [org.keycloak.services] (main) KC-SERVICES0030: Full model import requested. Strategy: IGNORE_EXISTING
INFO [org.keycloak.exportimport.util.ImportUtils] (main) Realm 'demo-realm' imported
# Second boot (after editing JSON, same database)
INFO [org.keycloak.services] (main) KC-SERVICES0030: Full model import requested. Strategy: IGNORE_EXISTING
INFO [org.keycloak.exportimport.util.ImportUtils] (main) Realm 'demo-realm' already exists. Import skipped
--import-realm is a first-boot bootstrap mechanism, not a declarative state reconciler. To apply ongoing config changes against a persistent database, use the Admin REST API or an IaC tool like the Terraform Keycloak Provider.
According to the official Importing and Exporting Realms docs,
kc.sh exportexcludes active sessions and event logs. Don’t use it as a production backup—back up PostgreSQL directly withpg_dumpor storage snapshots.
OIDC flows: PKCE and Client Credentials
Keycloak splits OIDC clients into two main models depending on whether the caller can safely hold a secret.
| Dimension | Public Client (demo-spa) | Confidential Client (demo-worker) |
|---|---|---|
| Typical caller | Browser SPA, native mobile app | Backend service, batch worker, internal API |
| Client secret | None (publicClient: true) | Stored securely (publicClient: false) |
| Recommended grant | Authorization Code + PKCE (S256) | Authorization Code (+PKCE) or client_credentials |
| Issues ID Token | Yes (with openid scope) | No (client_credentials issues Access Token only) |
Public Client: PKCE S256, JWKS verification, and /userinfo
When demo-spa enforces pkce.code.challenge.method: "S256", hitting /auth without a code_challenge triggers a 302 error redirect (error=invalid_request, Missing parameter: code_challenge_method). Even after login succeeds and returns an authorization code, submitting a mismatched code_verifier to /token fails with 400 invalid_grant:
1
2
HTTP/1.1 400 Bad Request
{"error": "invalid_grant", "error_description": "PKCE verification failed: Code mismatch"}
With the matching code_verifier, Keycloak returns 200 OK along with the access_token and id_token. Your API server fetches the public key matching the JWT header’s kid from jwks_uri to verify the RS256 signature. Passing that Access Token to userinfo_endpoint returns 200 OK with the user’s claims:
1
2
3
4
5
6
7
8
9
{
"sub": "86da39f5-9006-47fd-b9e9-85e9c974cdf8",
"email_verified": true,
"name": "Alice Kim",
"preferred_username": "alice",
"given_name": "Alice",
"family_name": "Kim",
"email": "alice@example.test"
}
If you script local HTTP login tests with non-browser clients like Python
requests, watch out for cookie flags. Keycloak 26 marks login session cookies (AUTH_SESSION_ID, etc.) asSecureeven understart-dev. Browsers treathttp://localhostas a secure context and send them, while plain HTTP libraries dropSecurecookies over HTTP and hitRestart login cookie not found. For the PKCES256protocol details, see my OAuth 2.1 and PKCE S256 post.
Confidential Client: client_credentials for M2M calls
For backend-to-backend calls with no human user, create a Confidential Client (demo-worker) with serviceAccountsEnabled: true:
1
2
3
4
5
curl -s -X POST "http://localhost:8080/realms/demo-realm/protocol/openid-connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" \
-d "client_id=demo-worker" \
-d "client_secret=demo-worker-secret"
With valid credentials, Keycloak returns 200 OK with an access_token (no id_token), setting preferred_username to service-account-demo-worker and azp to demo-worker. A wrong secret fails immediately with 401:
1
2
3
4
{
"error": "unauthorized_client",
"error_description": "Invalid client or Invalid client credentials"
}
Access Token roles and Audience mapper setup
When a resource server authorizes requests using a Keycloak Access Token, three claims matter most: realm_access, resource_access, and aud.
Decoding the Access Token for alice—who holds the Realm Role app-user and the demo-api Client Role order:read—shows how Keycloak separates the two scopes:
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"aud": "demo-api",
"azp": "demo-spa",
"preferred_username": "alice",
"realm_access": {
"roles": ["app-user"]
},
"resource_access": {
"demo-api": {
"roles": ["order:read"]
}
}
}
Notice why alice already has "aud": "demo-api". Keycloak’s built-in roles Client Scope includes an audience resolve mapper, which automatically adds every client ID found in resource_access into the aud claim.
The surprise happens with callers that don’t hold a demo-api Client Role. Both bob (who only has the Realm Role app-user) and demo-worker (an M2M service account) have no demo-api entry in resource_access, so their tokens default to "aud": "account". Any API server enforcing aud == "demo-api" will reject them with 401.
To fix this cleanly, create a demo-api-audience Client Scope with an Audience Protocol Mapper (oidc-audience-mapper) pointing to demo-api, and attach it as a Default Client Scope on demo-spa and demo-worker:
1
2
3
4
5
6
7
8
9
10
{
"name": "demo-api-audience-mapper",
"protocol": "openid-connect",
"protocolMapper": "oidc-audience-mapper",
"config": {
"included.client.audience": "demo-api",
"id.token.claim": "false",
"access.token.claim": "true"
}
}
Re-issuing tokens after attaching the mapper updates the aud claim as follows:
| Caller | aud before Audience mapper | aud after Audience mapper |
|---|---|---|
alice (has demo-api Client Role) | "demo-api" (via audience resolve) | "demo-api" |
bob (Realm Role app-user only) | "account" | ["demo-api", "account"] |
demo-worker (client_credentials) | "account" | ["demo-api", "account"] |
To map realm_access and resource_access into Spring Security authorities on the API side, see mapping Keycloak 26 roles in Spring Security 6.
Production mode and reverse proxy routing
In production, drop start-dev and H2 in favor of PostgreSQL and start. When Nginx, Traefik, or Caddy terminates TLS in front of Keycloak, configure Hostname v2 and KC_PROXY_HEADERS. The old KC_PROXY=edge option is gone—use KC_PROXY_HEADERS=xforwarded with KC_HTTP_ENABLED=true.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# compose.prod.yaml (key settings)
services:
keycloak:
image: quay.io/keycloak/keycloak:26.8.2
command: start
environment:
KC_DB: postgres
KC_DB_URL: jdbc:postgresql://postgres:5432/keycloak
KC_DB_USERNAME: keycloak
KC_DB_PASSWORD: ${KC_DB_PASSWORD}
KC_HOSTNAME: https://auth.example.test
KC_HOSTNAME_BACKCHANNEL_DYNAMIC: "true"
KC_PROXY_HEADERS: xforwarded
KC_HTTP_ENABLED: "true"
KC_HOSTNAME_BACKCHANNEL_DYNAMIC=true solves a common Docker Compose headache. Browsers reach Keycloak through the external HTTPS domain (https://auth.example.test), while backend containers on the same Docker network want to call http://keycloak:8080 for token exchange and JWKS without breaking iss validation.
Querying the Discovery endpoint in Profile prod activated from both paths produces this split:
| Discovery field | External proxy (X-Forwarded-*) | Internal Docker network (http://keycloak:8080) |
|---|---|---|
issuer | https://auth.example.test/realms/demo-realm | https://auth.example.test/realms/demo-realm |
authorization_endpoint | https://auth.example.test/.../auth | https://auth.example.test/.../auth |
end_session_endpoint | https://auth.example.test/.../logout | https://auth.example.test/.../logout |
token_endpoint | https://auth.example.test/.../token | http://keycloak:8080/.../token |
jwks_uri | https://auth.example.test/.../certs | http://keycloak:8080/.../certs |
userinfo_endpoint | https://auth.example.test/.../userinfo | http://keycloak:8080/.../userinfo |
Front-channel URLs (issuer, login, logout) stay anchored to the public HTTPS domain, while back-channel URLs (token, jwks_uri, userinfo) adapt to the internal request host. I used this same pattern when integrating a containerized PHP app in my Gnuboard 5 Keycloak OIDC SSO setup.
If you enable
KC_HOSTNAME_BACKCHANNEL_DYNAMIC=trueand omit thehttps://scheme fromKC_HOSTNAME(passingauth.example.testinstead ofhttps://auth.example.test), Keycloak exits with code1and logsERROR: hostname-backchannel-dynamic must be set to false if hostname is not provided as full URL. Always pass the full URL.
Summary
Before promoting a Keycloak 26 setup from local testing to production, run through these five checks:
- Replace the temporary admin: Sign in once with
KC_BOOTSTRAP_ADMIN_*, create a permanent admin inmaster, and delete the temporary account. - Isolate realms and back up PostgreSQL: Keep app users out of
master, and rely on database backups rather thankc.sh export. - Lock down client types: Require PKCE
S256on Public Clients and isolate M2M traffic inclient_credentialsConfidential Clients. - Verify
audfor every caller: Add an Audience Protocol Mapper whenever Realm-Role-only users or service accounts call APIs with strictaudchecks. - Pin Hostname v2 and proxy headers: Run
startwith PostgreSQL, pass a full URL inKC_HOSTNAME, setKC_PROXY_HEADERS=xforwarded, and turn onKC_HOSTNAME_BACKCHANNEL_DYNAMIC=truewhen containers share an internal network.