Keycloak SSO for microservices: deployment guide
Every microservice that rolls its own login is security debt with compound interest. One service stores hashes with an outdated algorithm, another issues tokens that never expire, and a third still has a “temporary” user that’s been active for three years. When an audit comes around, nobody knows who can access what.
The classic fix is to buy a commercial identity platform, with licenses that scale per active user. There’s another option: Keycloak, an open-source project under the Apache 2.0 license, maintained under the CNCF umbrella, offering SSO, identity federation, MFA and role management with no licensing cost.
In this guide you’ll see how to deploy it with a production mindset, how to connect your microservices, and which mistakes to avoid so centralized authentication doesn’t become your new single point of failure.
Why Keycloak fits a microservices architecture
Keycloak implements the standards that underpin modern identity today: OpenID Connect (OIDC), OAuth 2.0 and SAML 2.0. That means it doesn’t lock you into a proprietary SDK. Any framework with OIDC support, whether Spring Security, ASP.NET, FastAPI, NestJS or Envoy, can integrate without custom code.
What you get from centralizing:
- A single place for users, roles and policies. Offboarding someone is one operation, not twenty.
- Signed, verifiable tokens without calling the server. Each service validates the JWT with the public key published at the JWKS endpoint.
- Real SSO across applications. The user authenticates once and gets access to the whole ecosystem.
- Federation. Connect LDAP, Active Directory or external providers like Google or GitHub without touching your services.
- MFA, password policies and brute-force protection configurable from the console.
The real cost isn’t the license, it’s running it well. That’s what the rest of this article is about.
Reference architecture
Before writing a single line of configuration, it’s worth settling the design:
- Reverse proxy or ingress with TLS in front of Keycloak.
- Keycloak in at least two instances for high availability.
- PostgreSQL as the persistent database. Don’t use the embedded database outside of development.
- Optional API gateway that validates tokens before they reach the services.
- Microservices as resource servers: they receive a Bearer token, validate it and enforce authorization.
The flow is simple. The frontend redirects the user to Keycloak, which authenticates them and returns a code that’s exchanged for tokens. From there, the frontend calls the APIs with the access token and each service decides based on the JWT claims.
Base deployment with Docker Compose
For a realistic test environment or a single server, Docker and PostgreSQL are enough. This docker-compose.yml starts Keycloak in production mode behind a proxy:
services:
postgres:
image: postgres:16
environment:
POSTGRES_DB: keycloak
POSTGRES_USER: keycloak
POSTGRES_PASSWORD: ${KC_DB_PASSWORD}
volumes:
- kc_pgdata:/var/lib/postgresql/data
keycloak:
image: quay.io/keycloak/keycloak:26.0
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.midominio.com
KC_HTTP_ENABLED: "true"
KC_PROXY_HEADERS: xforwarded
KC_HEALTH_ENABLED: "true"
KC_METRICS_ENABLED: "true"
KC_BOOTSTRAP_ADMIN_USERNAME: admin
KC_BOOTSTRAP_ADMIN_PASSWORD: ${KC_ADMIN_PASSWORD}
depends_on:
- postgres
ports:
- "8080:8080"
volumes:
kc_pgdata:
A few details make all the difference:
- Use
start, neverstart-dev. Development mode disables security checks and template caching. KC_PROXY_HEADERSmust match what your proxy sends. Get it wrong and you’ll see redirects to internal URLs or invalid issuer errors.- Management ports (health and metrics) are exposed on a separate port in recent versions. Don’t publish them to the internet.
- Bootstrap credentials are only there to create your first real administrator. Afterwards, delete the temporary user.
Designing realms, clients and roles
This is where most deployments go wrong. The usual mistake is using the master realm for everything. Reserve master for administering Keycloak and create a dedicated realm per environment or business domain, for example produccion or plataforma-interna.
One client per application, with the right type
- Frontend web apps (SPAs or mobile): public client with the Authorization Code + PKCE flow. Never store a secret in the browser.
- Backends with a user session: confidential client with a client secret or signed-key authentication.
- Service-to-service communication: client credentials flow with a service account, so no service uses a person’s credentials.
- Pure APIs: they don’t need login; they only validate tokens. Just define their audience and roles.
Roles and scopes with a purpose
Prefer client roles (facturacion:lectura, facturacion:admin) over global realm roles, which end up as a catch-all. Group permissions into groups and assign roles to groups, not individual users. With client scopes and mappers you control which claims travel in the token. The smaller the token, the less you leak and the lighter each request is.
How microservices validate tokens
Each service only needs to know the issuer. Keycloak publishes its configuration at:
https://auth.midominio.com/realms/produccion/.well-known/openid-configuration
In Spring Boot, integration comes down to a single property:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://auth.midominio.com/realms/produccion
The service downloads the public keys, caches them and verifies signature, expiry, issuer and audience without calling Keycloak on every request. That’s exactly what makes this model scale.
Three golden rules for validation:
- Always validate the audience (
aud). A token issued for service A must not work on service B. - Keep access tokens short-lived, between 5 and 10 minutes, and rely on refresh tokens to renew the session.
- Propagate the token between services or, better yet, use token exchange or client credentials when the service acts on its own behalf.
If you have an API gateway, you can centralize validation at the edge and forward only the necessary claims to internal services. Even so, don’t blindly trust the internal network: critical services should re-verify the token.
High availability and performance
A single Keycloak instance is an operational risk: if it goes down, nobody can log in. Already-issued tokens stay valid until they expire, but renewals and new logins grind to a halt.
For production:
- Deploy at least two replicas against the same database. Keycloak uses Infinispan to share sessions and cache across nodes; on Kubernetes, tune the cache stack for DNS discovery.
- Size the database first. Most bottlenecks show up in PostgreSQL, not Keycloak. Use a connection pool and standby replicas.
- Configure health probes (liveness and readiness) pointing at the health endpoints.
- Monitor metrics with Prometheus: login latency, authentication errors and JVM usage.
- Pin versions. Upgrade in a controlled way and read the migration notes, because configuration options change between major versions.
Security: protect the guardian
Centralizing identity also concentrates risk, so Keycloak deserves stronger hardening than the rest of the platform.
- Expose only what’s necessary. The admin console should only be reachable from a management network or VPN.
- Enable the realm’s brute-force detection and require MFA for administrators.
- Manage secrets outside the repository. Database passwords and client secrets belong in a dedicated manager; if you don’t have one yet, see migrating from Vault to OpenBao in production for an open option.
- Throttle automated attacks at the edge. A public login endpoint attracts credential stuffing; leaning on Fail2ban on Linux servers over proxy logs adds a useful layer.
- Enable audit events (logins, errors, admin changes) and ship them to your centralized logging system.
And if you already use Keycloak as your identity provider, you can extend the same SSO to your infrastructure. Tools like Teleport let you replace SSH keys with audited access using federated OIDC authentication, so a single identity governs both applications and servers.
Configuration as code: reproducible and auditable
Configuring everything from the console works on day one and becomes unmanageable by the third environment. Treat realms as infrastructure:
- Export and import realms with the Keycloak command-line tool for ephemeral environments and testing.
- Use Terraform with the Keycloak provider to declare realms, clients, roles and mappers under version control.
- Review changes via pull request, just like any other infrastructure change.
- Test your restores. A PostgreSQL backup you’ve never restored is just a hope.
This discipline lets you replicate production in staging with a single command and catch configuration drift before it causes incidents.
Common mistakes to avoid
Misconfigured hostname. It causes issuer failures and redirect loops. Define the public URL explicitly and verify the proxy sends the correct headers.
Tokens that are too large. Packing in hundreds of roles and attributes inflates HTTP headers until the proxy returns 431 errors. Limit claims to the bare minimum.
One client for everything. Sharing credentials across services kills traceability and the ability to revoke access selectively.
Ignoring key expiration. If you rotate signing keys, services must refresh the JWKS. Use libraries that do it automatically.
Upgrading without testing. Keycloak moves fast. A staging environment with representative data prevents nasty surprises.
From deployment to an identity platform
Deploying Keycloak is the easy part; the real payoff comes when it becomes the identity contract for your entire platform. With well-designed realms, minimal clients, short tokens, versioned configuration and a redundant setup, you get what commercial solutions promise without vendor lock-in or per-user fees.
Start with a pilot service. Connect one API and one frontend, validate the PKCE flow, measure latency and, once the pattern is proven, migrate the rest of your microservices gradually. For advanced options, the official Keycloak documentation is the most reliable starting point. Every service that stops managing its own passwords is one less attack surface and one operational problem solved for good.