Identity and trust

Keycloak and Single Sign-On

1.What single sign-on is

Keycloak is an OpenID Connect and SAML identity provider (IdP). Apps send the browser to it, it checks the user (password, OTP, passkey or a brokered IdP) and returns signed tokens. One login leaves a session cookie at Keycloak that every app in the realm reuses : that is single sign-on. Keycloak 26.8.0, CNCF incubating.

Neighbours : the API server trusting these tokens is OIDC for the API server; what a groups claim grants is RBAC.

Four strings break SSOThe issuer URL, the redirect URI, the audience and the groups claim. Most login bugs are one of them not matching.

2.The model

ObjectWhat it isWatch out
RealmA tenant : own users, keys, issuer .../realms/<realm>master is for admins. No /auth since 17
ClientOne app that asks for tokensIts clientId shows up as azp in tokens
Public / confidentialNo secret (browser, CLI) / a secret or key for /tokenPublic : PKCE, tight redirect URIs
Client scopeBundle of mappers. Default : always. Optional : on requestNew realm defaults skip old clients
Protocol mapperPuts a claim in the ID token, access token or userinfoGroup Membership, Audience, ...
User, group, roleIdentities, memberships, realm and client rolesGroups nest, roles can be composite

3.Authorization code with PKCE

browser app (client) Keycloak (realm) 1 redirect to /auth + code_challenge 2 login (skipped with an SSO cookie) 3 back with code (60 s) via the browser 4 code + verifier back channel, /token 5 ID, access, refresh 6 check signature JWKS keys from /certs

Paths under https://<host>/realms/<realm>

EndpointPath
Discovery/.well-known/openid-configuration
Authorization/protocol/openid-connect/auth
Token.../token
Userinfo.../userinfo
Logout.../logout
JWKS keys.../certs

Grants : implicit SHOULD NOT be used, password grant MUST NOT be used (Keycloak, citing RFC 9700). Client credentials only for a client acting for itself. PKCE is optional per client until you set its method to S256.

4.Tokens and lifetimes

The basic claims are on OIDC for the API server. Keycloak adds :

  • azp : the client the token was issued to.
  • aud on a plain user token is account (Audience Resolve mapper plus the default account roles). A service that checks aud needs an Audience mapper.
  • groups comes from a Group Membership mapper. Full group path is ON in the admin console (/team). A mapper made by API or import without full.path acts OFF (team).
New realmDefault
Access token5 min (master 60 s)
SSO Session Idle30 min
SSO Session Max10 h
Offline Session Idle30 days
Authorization code60 s
  • microprofile-jwt writes a groups claim from realm roles, not groups.

The ID token's exp equals the access token's. Since 26.8.0 every refresh token's exp is capped by the session idle timeout, and a per-client lifespan cannot outlive SSO Session Max.

In short : A realm holds users, clients and keys behind one issuer URL. Apps use the code flow with PKCE and break when the issuer, redirect URI, audience or groups claim does not match.

1.Install paths

  • Official operator (lockstep) : kustomize ?ref=26.8.0 into a keycloak namespace you create first, raw manifests, experimental Helm chart, OLM. It runs the server, not the database : bring PostgreSQL 14 to 18 (CNPG).
  • codecentric keycloakx lags one release; default relativePath: /auth puts /auth in the issuer. Plain manifests : you own clustering and probes.

2.The Keycloak CR and what it makes

apiVersion: k8s.keycloak.org/v2beta1  # since 26.6.0
kind: Keycloak
spec:
  instances: 2
  image: registry.example.com/keycloak-custom:26.8.0
  db: {vendor: postgres, host: keycloak-pg}  # + Secrets
  http: {httpEnabled: true}    # TLS at the Gateway
  hostname: {hostname: auth.example.com}
  proxy: {headers: xforwarded}
  ingress: {enabled: false}    # HTTPRoute instead
  features: {enabled: ["client-admin-api:v2"]}
Gateway TLS ends here HTTPRoute Service:8080 / :9000 Keycloak CR operator makes to pods StatefulSetkeycloak-0, keycloak-1 keycloak-discoveryheadless, :7800 jdbc-ping : pods findeach other via the DB PostgreSQLstate + discovery

The CR also makes a NetworkPolicy, a temporary <name>-initial-admin Secret (replace it), a ServiceMonitor if metrics are on. Default memory: request 1700MiB, limit 2GiB. Never expose port 9000 (/health, /metrics).

3.Build time vs runtime options

OptionKindNotes
dbbuildDefault dev-file, not for production
health-enabled, metrics-enabledbuildDefault false
featuresbuild--features replaces the stored list
hostname, proxy-headers, http-enabledruntimeFine at each start
Exit code 2A custom spec.image (or startOptimized: true) starts --optimized : a build option passed at runtime with a different value exits with code 2. The stock image rebuilds at start. features.enabled must repeat the baked list.

4.Realms and clients as code

  • KeycloakRealmImport creates a realm once.
  • KeycloakOIDCClient (v2alpha1, Preview) needs client-admin-api:v2 and a Secret <cr-name>-admin. Name = clientId. No mappers, scopes, PKCE, lifetimes.
  • Since 26.8.0 its Secret needs label operator.keycloak.org/kind: KeycloakOIDCClient, else HasErrors.

5.Upgrades

update.strategyOn an image change
RecreateOnImageChangeDefault. Scales to 0 first : short outage
AutoRolls a newer patch, same major.minor
ExplicitRolls until you change spec.update.revision

Schema migration is one way : back up first. Roll back by restoring a dump into a fresh database.

Seen in practiceBuild options repeated at runtime crashloop an optimized image. Do better : bake them once, run 2+ instances, give the DB HA (one Postgres on local disk is a single point of failure), dump it nightly.
CommandWhat it does
kubectl apply -k 'github.com/keycloak/keycloak-k8s-resources/kubernetes?ref=26.8.0'Operator, into ns keycloak
kubectl -n keycloak get keycloaks/<name> -o jsonpath='{.status.conditions}'Ready, HasErrors
kubectl -n keycloak get keycloakoidcclient <name> -o yamlClient errors (only here)
kc.sh show-configBaked values show (Persisted)
In short : The operator runs Keycloak from one CR, not its DB. Bake build options into the image, never at runtime. Upgrade after a backup; roll back from a dump. Client CRs cover part of a client.

1.Clients that work

  • Redirect URIs match exactly, case-sensitive. * only as the last character : then a prefix match.
  • https://*.example.com/cb is a literal : it never matches.
  • Since 26.6.3 https://example.com* means https://example.com/*.
  • A portless plain-http loopback URI (localhost, 127.0.0.1) matches any port, for CLIs (OIDC auth).
  • Since 26.7.3 a redirect URI carrying OIDC response parameters is refused.
aud: account is normalAdd an Audience mapper (often in its own client scope) when a proxy or gateway checks aud. Since 26.6.2 introspection checks it too.

Post-logout redirect URIs are a separate list. A broken one does not break login, so it is easy to miss.

2.Ways to put SSO or a token check in front of an app

PatternCode flow runs inGood forWeak spot
Native OIDC in the appThe appRoles map to app rolesConfigure each app
oauth2-proxyThe proxy, serves /oauth2/*Mature, group checksExtra hop per app; no gRPC ext_authz mode
Envoy ext_authz serverThe auth server, inside ext_authz repliesOne deployment for many hostsIn-memory sessions mean one replica
Gateway-native OAuth2Envoy oauth2 filter : kgateway OAuth2, Envoy Gateway SecurityPolicyNo extra serviceGateway-specific config
Gateway JWT validationNone : client brings a bearer tokenAPIs and machine clientsNo browser login

3.The ext_authz path

GatewayExtensionextAuth: grpcService TrafficPolicytargetRefs: HTTPRoute browser Gateway(Envoy) app allow auth server Keycloak login Check deny + 302or allow login at Keycloak, then the callback returns through the Gateway : Set-Cookie
  • A kgateway GatewayExtension holds extAuth, oauth2 or jwt; a TrafficPolicy attaches it to an HTTPRoute by targetRefs. type is deprecated, a no-op.
  • Across namespaces it needs a ReferenceGrant, or it silently fails to attach.
# oauth2-proxy flags
--provider=keycloak-oidc
--oidc-issuer-url=https://auth.example.com/realms/demo
--code-challenge-method=S256
--reverse-proxy=true
--cookie-refresh=4m     # under the 5 min token
--allowed-group=/admins # full path

The kgateway jwt gate answers 401 for a missing or bad token and 403 when its CEL rule misses. CEL rbac entries are ORed : put AND inside one expression, and use in for list claims.

4.The issuer is the public URL

  • In-cluster clients that check iss must use the public URL, not keycloak-service.<ns>.svc.
  • The JWKS may come from the in-cluster Service. With a 5 minute JWKS cache, a longer Keycloak outage breaks token checks.
  • One Keycloak outage takes out every SSO app. Keep an escape hatch per app where one exists.
Seen in practiceAll four patterns can live in one cluster. Pitfalls : a hostname-wildcard redirect URI never matches, and a logout redirect left on one fails quietly. Pods may not hairpin to the LB IP. Do better : exact URIs per app, and reach the public issuer with hostAliases or split DNS.
In short : Register exact redirect URIs, add an Audience mapper where aud is checked, pick the pattern by where the code flow runs, and use the public issuer URL everywhere.