Keycloak Realm Configuration Best Practices: A Practical Guide

· 12 min read

Keycloak realm configuration best practices come down to four rules: one application realm per trust boundary, nothing but administration in master, every setting in version control, and hardened defaults before the first user signs in. A realm that was clicked together in the admin console will drift from its documented state, and drift is what eventually hurts you. This guide covers the decisions in the order I would make them.

Key takeaways- Use one realm per distinct user population or legal boundary, and keep the master realm for administering Keycloak only.- Set hostname, brute-force detection, password policy, SMTP and short token lifespans before the first real user exists.- Use authorization code with PKCE for public clients, exact redirect URIs, and client roles mapped through groups.- Manage the realm as code with Terraform or reviewed import JSON, and expect a few settings to need scripted API calls.- Pin the Keycloak version, scan the image in CI, and treat every release as a checklist run.

What good Keycloak realm configuration looks like

A good realm is small, explicit and reproducible. It has a clear reason to exist, a hostname that matches how users reach it, restrictive defaults, and a definition stored in a repository. If the realm were deleted, you could recreate it from code without remembering what someone clicked eight months ago.

What a realm actually is

A realm is an isolated namespace. It holds users, clients, roles, groups, sessions and identity providers, and none of these are visible to other realms. A user in one realm cannot log in to a client in another, and tokens are issued with a different issuer per realm.

That isolation is the whole point. It also means every realm is a separate configuration surface you must keep consistent.

Why drift is the real risk

Click-configured realms drift. Someone raises a token lifespan to debug a problem and forgets it. Someone adds a wildcard redirect URI "temporarily" in production. Nothing fails, so nobody notices.

Individual settings are rarely the problem. The problem is that you cannot answer the question "what is different from the baseline?" without a baseline. Code gives you that baseline, and a diff turns an invisible change into a reviewable one.

When to use one realm, several realms, or one per tenant

Separate isolated realm boxes with a distinct locked admin realm set apart from them
Separate isolated realm boxes with a distinct locked admin realm set apart from them

The right number of realms follows from who your users are, not from how many apps you have. I start from one realm and split only when a real boundary forces it.

Single realm versus several realms

Use a single realm when one user base is shared across several applications and you want single sign-on between them. A person logs in once and moves between the web app, the mobile app and the back office.

Use separate realms when user populations must not mix. Examples are staff and customers with different policies, or users under different legal regimes where data must be separated. Separate realms also let you set different password policies, themes and identity providers without conditionals.

Realm-per-tenant trade-offs

Realm-per-tenant gives strong isolation. A misconfigured role in one tenant cannot leak into another. The cost is operational. Each realm adds startup and memory overhead, another configuration to keep in sync, and more work at every upgrade. The cost grows with tenant count.

For a handful of large tenants with contractual isolation needs, it is reasonable. For hundreds or thousands of small tenants, I would look at a single realm and model tenants another way. Keycloak has been adding an organizations feature, which it introduced behind a realm-level switch, according to a Keycloak GitHub issue on enabling organizations. That is a clue about direction, not a guarantee of fit. Check the documentation for your version before designing around it.

Keep master for administering Keycloak

Do not put applications or end users in master. Create a dedicated administrator account with a strong credential, and do not leave the bootstrap admin in daily use. Restrict network access to the admin console so it is not reachable from the public internet; at the ingress level this usually means serving the admin paths only on an internal hostname or behind an allowlist.

Why so strict? A compromise of master can mean control of every realm. Keeping it out of the user path shrinks that exposure.

Practical rule: Create a realm only for a real trust or legal boundary, and never host applications in master.

How to configure the realm settings that matter first

Do these before launch. Each is cheap on day one and awkward after users and integrations depend on the defaults.

Hostname and frontend URL

Behind a Kubernetes ingress or reverse proxy, Keycloak must know the public hostname and scheme. Wrong values produce wrong issuer URLs in tokens and discovery documents, and resource servers that validate the issuer will reject them. The Keycloak securing applications guide lists validating access tokens among its recommendations, which is exactly where a mismatched issuer shows up.

Test it by fetching the realm's OpenID discovery document through the public address and checking that every URL uses your public hostname, for example https://auth.example.com/realms/app. Option names for hostname and proxy settings change between versions, so use the documentation for your pinned release.

Brute-force detection, password policy and verification

Turn on brute-force detection. Set a password policy that fits your risk, such as minimum length and a denylist rather than arbitrary complexity rules. Enable email verification and decide which required actions apply to new users.

Configure SMTP before launch. Verification and password reset both depend on email, and finding out they are broken during your first real signup is a poor way to learn it. Send a test message from the realm's email settings and confirm it arrives.

Token and session lifespans

Keep access tokens short. A short lifespan limits how long a stolen token is useful, and refresh tokens handle continuity. Bound the SSO session idle and maximum times so sessions end eventually. Enable offline sessions only for clients that truly need long-lived refresh, such as a mobile app, because offline tokens are effectively durable credentials.

I will not give a universal number here. The right values depend on your risk tolerance and user experience goals. Pick them deliberately, write them into code, and review them as a baseline.

Realm events and retention

Enable event logging for login errors and for admin events. Login errors support incident response, and admin events show who changed configuration. Set an expiration on stored events. Events contain personal data such as IP addresses and usernames, so retention without a limit is a GDPR problem. Pick a period you can justify and document it.

Practical rule: Before the first user, fix hostname, SMTP, brute-force protection, token lifespans and event retention.

How to design clients, roles and groups

Most realm incidents I would worry about live in client configuration. Treat each client as a small security contract.

Grant types and client types

Public clients, such as single-page and mobile apps, should use authorization code with PKCE. Confidential clients, such as backends, can hold a secret and use the code flow or client credentials for service accounts. The Keycloak securing applications guide documents the supported grant types, including implicit and resource owner password credentials.

Disable implicit and direct access grants unless a specific client requires them. Fewer enabled flows means fewer paths to abuse. Quarkus documents the same authorization code flow for protecting web applications in its OIDC code flow guide, which is useful if your backend is Quarkus.

Redirect URIs and web origins

Register exact redirect URIs. A wildcard such as https://app.example.com/* invites open-redirect and token-leak attacks if any page on that host can be abused. Set web origins explicitly rather than using a catch-all. The securing applications guide includes redirect URIs in its recommendations section, and I treat that as the most important client setting to review.

Roles and groups

Prefer client roles over realm roles. A client role belongs to one application, so names like admin do not collide across apps. Realm roles suit genuinely cross-application concepts. A DevSecOps Now overview of realm roles exists as a developer guide, but the page I saw was a tag archive with little detail, so rely on the official documentation for semantics.

Map groups to composite roles. Users join groups such as moderators, and the group carries a role bundle. Permissions stay readable, and onboarding becomes a group change instead of a list of individual grants.

Keep claims minimal

Use protocol mappers to add only what the application needs. Every claim travels with every request, so a large token slows each call and can exceed header size limits at a proxy. If a service needs rich profile data, fetch it from an API instead of stuffing it into the token.

Practical rule: One flow per client type, exact redirect URIs, client roles through groups, and the smallest token that works.

How to manage the realm as code

I manage identity as code with Keycloak and Terraform, and I would recommend that path for most teams. It makes changes reviewable and environments comparable.

Terraform or import JSON

Two approaches work. Terraform with the Keycloak provider gives you plans and diffs. Realm import JSON is simpler to start with and fits bootstrapping a new instance.

Avoid exporting a full realm and committing it unreviewed. Exports are large, include generated identifiers and noise, and bury meaningful settings. Hand-curate what you commit so a reviewer can read it.

Approach

Strength

Where it misleads

Terraform provider

Plan shows exact diff before apply

Provider can lag new Keycloak features

Realm import JSON

Fast bootstrap of a fresh realm

Import does not give you ongoing drift detection

Full export committed as-is

Captures everything quickly

Noisy, unreviewable, may contain environment specifics

Environments and promotion

Parameterize hostnames, redirect URIs and secrets with variables, one set per environment. Promote through CI: plan in staging, review the plan, apply, then repeat for production. This mirrors a zero-downtime release process, where nothing reaches production that a reviewer has not seen first.

Secrets

Keep secrets out of state where possible. Terraform state can hold sensitive values in plain form, so protect the backend and restrict access. Store client secrets in a secrets manager and inject them at deploy time.

The limitation

Provider coverage lags new Keycloak features, so some settings still need scripted calls to the admin API. Reliability can also be a concern. A Keycloak forum thread describes one user whose Terraform run sometimes did not create roles or user attributes. That is a single report in a dev environment, a clue and not proof of a general defect. It is a good reason to verify applied state after each run rather than trusting the exit code.

Reporting rule: A change is done only when the plan is clean after apply and the behavior is confirmed in the running realm.

Common mistakes and a short glossary

Frequent failures

  • Working in master instead of a dedicated realm.
  • Wildcard redirect URIs left from debugging.
  • Long-lived tokens set once and never revisited.
  • Manual hotfixes in production that never reach code.
  • Upgrading Keycloak without testing against a realistic export of your realm in staging.

Each of these is a drift problem in disguise. The fix is the same: code, review, and a repeatable test.

Version and image hygiene

Run a pinned Keycloak version, never a floating tag. Scan the image with Trivy in CI and fail builds on severities you decide in advance. Track CVEs so that patching is same-day work; I lead same-day CVE response across Kubernetes clusters, and the discipline is mostly having the pipeline ready before the advisory lands. If you deploy on Kubernetes, the official operator is now a common route, as a JANUA.FR post on operator-based deployment notes. It is a vendor's summary, so read the official operator documentation too.

Glossary

  • Realm: an isolated namespace of users, clients, roles and sessions.
  • Client: an application registered to request tokens.
  • Scope: a named set of claims or permissions a client may request.
  • Mapper: a rule that adds or transforms claims in tokens.
  • Federation: syncing users from an external store such as LDAP.
  • Identity provider: an external login source, such as another OIDC provider.
  • Flow: the ordered authentication steps a user passes through.
  • Event listener: a component that receives realm events, for logging or alerts.

If you would rather not operate it

Running Keycloak is real work. A managed option can remove it; RealmDeploy, a managed Keycloak on Kubernetes, is listed as coming soon. For a SaaS starter where auth just needs to exist, MakeV1: Ship your SaaS with the hard parts already done. ships auth already done. Both are alternatives to operating the identity server yourself, and the trade-off is less control for less toil. For more on how I approach this, see my background running platform, security and identity, more platform engineering notes, and my side projects.

Run this realm review checklist every release

  1. Confirm the realm lives in code and the plan shows no unexpected diff.
  2. Verify brute-force detection, password policy and token lifespans match the baseline.
  3. Audit redirect URIs, web origins and enabled grant types for every client.
  4. Review role and group changes, and remove unused clients and users.
  5. Test login, refresh and logout in staging, then upgrade Keycloak and rescan the image.
Keycloak Realm Configuration Best Practices: A Practical Guide - Ali Hesari