Skip to main contentSkip to user menuSkip to navigation

Keycloak

Master Keycloak: identity and access management, SSO, federation, and enterprise authentication.

35 min readIntermediate
Not Started
Loading...

What is Keycloak?

Keycloak is an identity and access management server. Applications redirect people to Keycloak to sign in, and APIs trust tokens that Keycloak issues. This keeps password handling, single sign-on, multi-factor authentication, identity federation, sessions, and protocol configuration in one deliberate security boundary.

Keycloak can store users itself or connect to LDAP, Active Directory, and external OpenID Connect or SAML identity providers. It exposes OpenID Connect, OAuth 2.0, and SAML endpoints so applications do not need to invent their own login protocol.

Keycloak does not replace application authorization

Keycloak can issue roles, groups, scopes, and other claims, but each API must still validate the token and enforce resource ownership, tenant boundaries, and business rules. A valid token is not permission to access every object.

Identity boundary

Realm

A realm owns its users, clients, roles, sessions, authentication flows, and signing keys. The master realm administers the server; application identities belong in purpose-built realms.

Application contract

Client

A client represents an application or service. Its settings define redirect URIs, allowed protocol capabilities, credentials, scopes, and claim mappings.

Who verifies the user?

Identity source

Keycloak can verify a local credential, federate a directory, or broker login to an external identity provider while presenting one protocol contract to applications.

Continuity and evidence

Session and token

The Keycloak session enables SSO. ID, access, and refresh tokens carry different evidence and lifetimes; applications must use each only for its intended audience.

Review OAuth 2.0 first if authorization codes, PKCE, audiences, or scopes are unfamiliar. Keycloak implements those protocols; it does not change their trust model.

Configure each client from where its secrets can live

In Keycloak, Client authentication On creates a confidential client that must authenticate at the token endpoint. Off creates a public client that cannot safely protect a shared secret. That distinction follows the application's execution environment, not the administrator's preference.

Lab 1: harden the client contract

Choose an application shape, then deliberately enable the wrong capability, remove PKCE, expose a wildcard redirect, or pretend a browser can hold a client secret. The lab maps those choices to the names used in Keycloak's client settings.

Client hardening lab

Load the Keycloak client model

The lesson-owned client profiles and capability constraints are loading.

Loading Keycloak client boundaries...

The safe starting points are:

  • Server-rendered web application
    • Enable Client authentication and Standard flow.
    • Require PKCE S256 and exchange the code on the backend.
    • Store client credentials and tokens outside the browser.
  • Single-page or native application
    • Disable Client authentication because distributed code cannot protect a shared secret.
    • Enable Standard flow, require PKCE S256, and register specific redirect URIs.
    • Keep Implicit flow and Direct access grants disabled.
  • Machine service
    • Enable Client authentication and Service account roles.
    • Grant only the service-account roles the workload needs.
    • Disable browser and password-based capabilities that the workload never uses.

The current Keycloak client guide defines these capability switches. The OAuth 2.0 Security Best Current Practice explains why the implicit and password grants are unsuitable for new designs.

Trace one browser login before adding features

An OpenID Connect login is a sequence of boundaries. The browser carries redirects; the backend or public client completes the code exchange; the API evaluates the access token. Keep the responsibilities separate.

  1. 1

    Application

    Start authorization

    Create transaction state and a PKCE verifier, then redirect the browser to the realm's authorization endpoint with an exact registered callback.

  2. 2

    Keycloak

    Establish identity

    Keycloak reuses an eligible SSO session or runs the realm's authentication flow. It may verify a local credential or broker the user to an external identity provider.

  3. 3

    Token endpoint

    Redeem the code

    The client sends the one-time code and PKCE verifier to the token endpoint. A confidential client also authenticates using its configured credential.

  4. 4

    Application and API

    Enforce the token

    The client validates the ID token for its login transaction. The API independently validates the access token's signature, issuer, audience, expiry, and required scope before applying application authorization.

Do not merge the token roles

  • ID token: an OpenID Connect identity assertion for the client. It is not the API's authorization credential.
  • Access token: a credential for a resource server. The API must reject a token minted for another audience.
  • Refresh token: a credential used at the token endpoint to obtain replacement tokens. Do not send it to APIs or place it in URLs and logs.
  • Keycloak session: server-side login continuity that can connect several client sessions. Token expiry, session expiry, and logout propagation are related but not identical controls.

Treat realms, groups, roles, and scopes as different controls

A realm is the broadest administrative and cryptographic boundary in this model. Clients, groups, roles, and client scopes organize policy inside it; they are not interchangeable tenant-isolation mechanisms.

Keys and administration

Realm boundary

Use a separate realm when identities, signing keys, login policy, administrators, or protocol endpoints require strong separation. Realm count also creates operational work for upgrades, configuration, monitoring, and incident response.

Membership structure

Groups

Groups organize users and can carry inherited role mappings or attributes. A group describes membership; it does not by itself prove permission to a particular object.

Coarse entitlement

Roles

Realm and client roles can express broad capabilities. Keep composites understandable, and avoid placing every entitlement into every access token.

Claim contract

Client scopes

Client scopes package protocol mappers and role-scope mappings. Use them to control which claims and scopes a client can request or receives by default.

Before creating one realm per customer, name the isolation requirement: separate administrators, keys, identity policy, branding, data residency, or only application membership. Choose the boundary from that requirement and test onboarding, export, backup, recovery, and offboarding at the expected realm count.

Compose authentication flows without creating bypasses

An authentication flow is an ordered decision graph that determines how Keycloak establishes identity. Executions can be required, alternative, conditional, or disabled. A polished login page does not compensate for a branch that silently skips the intended assurance.

Build flows in this order:

  1. Name the assurance outcome. Decide when password, OTP, WebAuthn, identity brokering, or another approved authenticator is sufficient.
  2. Define recovery separately. Enrollment, lost-device recovery, email actions, and administrator resets can become weaker alternate login paths.
  3. Bind step-up to risk and action. Require stronger authentication for sensitive operations instead of forcing one static flow onto every request.
  4. Test every branch. Exercise new users, existing SSO sessions, federated users, missing attributes, failed authenticators, locked accounts, and unavailable dependencies.

For external identity stores, decide whether Keycloak imports data, reads it on demand, or delegates credential validation. Then rehearse directory latency, duplicate identifiers, mapper changes, disabled users, and provider outages. Federation moves an identity dependency; it does not remove it.

Rotate signing keys with an intentional overlap

Keycloak has one selected active signing key and may retain passive keys for verification. During a planned rotation, the new active key signs new tokens while the old passive key remains available long enough for previously issued tokens to expire.

Lab 2: decide when the old key may stop verifying

Set the longest old-token lifetime and elapsed overlap, then compare a planned rotation with a compromised-key response. Advance through the key states and inspect which tokens continue to validate.

Signing-key lifecycle lab

Load the realm-key model

The lesson-owned rotation stages and incident modes are loading.

Loading realm-key lifecycle...

The arithmetic is deliberately small and visible:

remaining old-token window = max(0, longest accepted old-token lifetime - elapsed overlap)

This is a planning bound, not a claim about a Keycloak default. Inventory the actual access, ID, offline, action-token, and client-cache behavior in your realm before retiring a key.

For a suspected compromise, waiting preserves the attacker's validation path. The Keycloak realm-key guide directs operators to create a new pair and remove the compromised pair immediately. It also describes a Keycloak not-before push for configured clients; verify which of your clients honor that mechanism and plan forced reauthentication separately.

Deploy Keycloak as a stateful security service

A production request crosses more than a Keycloak process. The public hostname, reverse proxy, realm configuration, database, distributed caches, identity providers, email delivery, and protected applications all participate in login and recovery.

Production authentication path

Keep public, management, persistence, and downstream trust boundaries explicit.

Protocol client

Browser or workload

Starts OIDC or SAML, carries redirects, and presents the resulting credential only to its intended recipient.

Public edge

Trusted reverse proxy

Terminates or passes TLS according to one documented model, overwrites forwarded headers, and restricts administration paths.

Identity control plane

Keycloak nodes

Run the same build and realm policy, participate in cache discovery, and expose health and metrics on a protected management interface.

Durable dependencies

Database and identity stores

Persist Keycloak state and resolve federated identities. Their latency, backup, consistency, and failure behavior are part of authentication availability.

Enforcement boundary

Application and API

Validate discovery metadata and tokens, apply local authorization, and handle key refresh, issuer outages, logout, and expired credentials predictably.

Use supported deployment guidance and benchmark your own realm, extensions, login flows, token shape, identity providers, and traffic mix. User count alone cannot predict memory, login latency, database storage, or availability.

The Keycloak high-availability guide documents supported topologies and explicitly marks experimental options. Do not copy a topology without checking the documentation for the Keycloak version you deploy.

Start production with explicit network boundaries

This configuration assumes an edge proxy terminates TLS, reaches Keycloak over a private HTTP network, overwrites X-Forwarded-* headers, and is restricted to the listed CIDR. Secrets stay in environment variables or the platform's secret mechanism, not in this file.

Keycloak configuration behind an edge TLS proxy

Keycloak's current reverse-proxy guidance separates the application listener from the management interface. Do not publish management port 9000 through the public proxy. Restrict the Admin Console and Admin REST API at the network and reverse-proxy layer; an alternate admin hostname alone does not remove the API from the frontend hostname.

See the official hostname, reverse proxy, and management interface guides for the exact options and threat model.

Validate access tokens at the API boundary

This TypeScript example uses OpenID Connect discovery and a remote JWKS through the maintained jose library. It pins issuer, audience, algorithm, expiry, and required scopes before application code receives the claims.

Verify a Keycloak access token before authorization

Production verification also needs bounded network timeouts, cached-key refresh behavior, telemetry that never logs credentials, and a policy for issuer or JWKS unavailability. After cryptographic validation, enforce tenant ownership and object-level authorization from trusted application data.

Review the production boundary

Identity and client policy

  • Keep application users and administrators out of the master realm.
  • Register exact redirect URIs and narrow web origins; never use a full wildcard in production.
  • Disable unused flows and capabilities on every client.
  • Require MFA or stronger authenticators for privileged administration.
  • Review role composites, protocol mappers, default client scopes, and token size.

Runtime and dependencies

  • Run production mode with a supported external database and tested backups.
  • Pin and test the public hostname, TLS model, proxy headers, and trusted proxy addresses.
  • Protect health, metrics, administration, and database endpoints from public access.
  • Benchmark login, refresh, logout, federation, and key-refresh traffic with production-like flows.
  • Rehearse node, zone, database, directory, email, and external identity-provider failures.

Operations and incident response

  • Export configuration through a reviewed, repeatable process and detect policy drift.
  • Patch Keycloak, providers, themes, and extensions on a tested release cadence.
  • Alert on login failures, lockouts, token errors, dependency latency, database saturation, cache health, and administrator actions without recording secrets or tokens.
  • Rotate realm keys and client credentials, and test the overlap or revocation behavior.
  • Verify restore, forced logout, compromised administrator, and compromised signing-key runbooks.
No quiz questions available
Could not load questions file
Spotted an issue or have a better explanation? This page is open source.Edit on GitHub·Suggest an improvement