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.
2.The model
| Object | What it is | Watch out |
|---|---|---|
| Realm | A tenant : own users, keys, issuer .../ | master is for admins. No /auth since 17 |
| Client | One app that asks for tokens | Its clientId shows up as azp in tokens |
| Public / confidential | No secret (browser, CLI) / a secret or key for /token | Public : PKCE, tight redirect URIs |
| Client scope | Bundle of mappers. Default : always. Optional : on request | New realm defaults skip old clients |
| Protocol mapper | Puts a claim in the ID token, access token or userinfo | Group Membership, Audience, ... |
| User, group, role | Identities, memberships, realm and client roles | Groups nest, roles can be composite |
3.Authorization code with PKCE
Paths under https://<host>/
| Endpoint | Path |
|---|---|
| Discovery | /.well-known/ |
| Authorization | /protocol/ |
| Token | .../ |
| Userinfo | .../ |
| Logout | .../ |
| JWKS keys | .../ |
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.audon a plain user token isaccount(Audience Resolve mapper plus the defaultaccountroles). A service that checksaudneeds an Audience mapper.groupscomes from a Group Membership mapper. Full group path is ON in the admin console (/team). A mapper made by API or import withoutfull.pathacts OFF (team).
| New realm | Default |
|---|---|
| Access token | 5 min (master 60 s) |
| SSO Session Idle | 30 min |
| SSO Session Max | 10 h |
| Offline Session Idle | 30 days |
| Authorization code | 60 s |
microprofile-jwtwrites agroupsclaim 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.
1.Install paths
- Official operator (lockstep) : kustomize
?ref=26.8.0into akeycloaknamespace you create first, raw manifests, experimental Helm chart, OLM. It runs the server, not the database : bring PostgreSQL 14 to 18 (CNPG). - codecentric
keycloakxlags one release; defaultrelativePath: /authputs/authin 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"]}
The CR also makes a NetworkPolicy, a temporary <name>- 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
| Option | Kind | Notes |
|---|---|---|
db | build | Default dev-file, not for production |
health-enabled, metrics-enabled | build | Default false |
features | build | --features replaces the stored list |
hostname, proxy-headers, http-enabled | runtime | Fine at each start |
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
KeycloakRealmImportcreates a realm once.KeycloakOIDCClient(v2alpha1, Preview) needsclient-admin-api:v2and a Secret<cr-name>-. Name =admin clientId. No mappers, scopes, PKCE, lifetimes.- Since 26.8.0 its Secret needs label
operator., elsekeycloak.org/ kind: KeycloakOIDCClient HasErrors.
5.Upgrades
update. | On an image change |
|---|---|
RecreateOnImageChange | Default. Scales to 0 first : short outage |
Auto | Rolls a newer patch, same major.minor |
Explicit | Rolls until you change spec. |
Schema migration is one way : back up first. Roll back by restoring a dump into a fresh database.
| Command | What it does |
|---|---|
| kubectl apply -k 'github.com/ | Operator, into ns keycloak |
| kubectl -n keycloak get keycloaks/ | Ready, HasErrors |
| kubectl -n keycloak get keycloakoidcclient <name> -o yaml | Client errors (only here) |
| kc.sh show-config | Baked values show (Persisted) |
1.Clients that work
- Redirect URIs match exactly, case-sensitive.
*only as the last character : then a prefix match. https://*.example.com/cbis a literal : it never matches.- Since 26.6.3
https://example.com*meanshttps://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
| Pattern | Code flow runs in | Good for | Weak spot |
|---|---|---|---|
| Native OIDC in the app | The app | Roles map to app roles | Configure each app |
| oauth2-proxy | The proxy, serves /oauth2/* | Mature, group checks | Extra hop per app; no gRPC ext_authz mode |
| Envoy ext_authz server | The auth server, inside ext_authz replies | One deployment for many hosts | In-memory sessions mean one replica |
| Gateway-native OAuth2 | Envoy oauth2 filter : kgateway OAuth2, Envoy Gateway SecurityPolicy | No extra service | Gateway-specific config |
| Gateway JWT validation | None : client brings a bearer token | APIs and machine clients | No browser login |
3.The ext_authz path
- A kgateway
GatewayExtensionholdsextAuth,oauth2orjwt; aTrafficPolicyattaches it to an HTTPRoute bytargetRefs.typeis 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
issmust use the public URL, notkeycloak-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.
hostAliases or split DNS.aud is checked, pick the pattern by where the code flow runs, and use the public issuer URL everywhere.