Keycloak is the most widely adopted open-source Identity and Access Management (IAM) platform in the world. Backed by Red Hat and used by organizations ranging from startups to Fortune 500 companies, it provides enterprise-grade authentication and authorization without per-user licensing fees. This guide covers everything you need to know about Keycloak – from your first Docker container to a production-ready, highly available cluster.

Whether you are evaluating Keycloak for a new project, migrating from a commercial IAM vendor, or looking to deepen your expertise, this page links to every Keycloak resource on this site and provides the context to navigate them effectively. If you are completely new, start with Getting Started with Keycloak and come back here as a reference.

What is Keycloak

Keycloak is an open-source Identity and Access Management solution that provides Single Sign-On (SSO), identity brokering, user federation, and fine-grained authorization services. Originally created by Red Hat, it is now a Cloud Native Computing Foundation (CNCF) incubating project, which signals long-term community governance and vendor neutrality.

At its core, Keycloak acts as a centralized authentication server. Your applications delegate login to Keycloak, which handles credential verification, session management, and token issuance. Applications never see raw passwords – they receive cryptographically signed tokens (JWTs) that assert user identity and permissions.

Key Features

  • Single Sign-On and Single Sign-Out – Users authenticate once and gain access to all connected applications. Logging out of one application terminates sessions across all of them.
  • Standard Protocols – Native support for OAuth 2.0, OpenID Connect (OIDC), and SAML 2.0. This means Keycloak works with virtually any framework or language that supports these standards.
  • Identity Brokering – Connect to external identity providers like Google, GitHub, Facebook, or any SAML/OIDC provider. Users can log in with their existing accounts.
  • User Federation – Sync users from LDAP servers and Active Directory without migrating them. Keycloak authenticates against the directory in real time.
  • Admin Console – A full-featured web UI for managing realms, users, roles, clients, and authentication flows.
  • Account Console – A self-service portal where users manage their own profiles, passwords, sessions, and linked accounts.
  • Fine-Grained Authorization – Policy-based access control using attributes, roles, groups, JavaScript, or custom policies.
  • Extensible Architecture – Service Provider Interfaces (SPIs) let you plug in custom authenticators, user storage providers, event listeners, and protocol mappers.

Common Use Cases

Keycloak fits a wide range of scenarios. Enterprises use it to centralize identity across internal applications. SaaS companies use it as their customer identity platform. DevOps teams deploy it to protect APIs and microservices. Government agencies and healthcare organizations choose it for on-premises deployments where data sovereignty is non-negotiable.

Getting Started with Docker

The fastest way to get Keycloak running is with Docker. A single command gives you a fully functional instance:

docker run -d --name keycloak \
  -p 8080:8080 \
  -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
  -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
  quay.io/keycloak/keycloak:26.0 start-dev

After the container starts, open http://localhost:8080 in your browser and log in with admin / admin. You will land on the Keycloak Admin Console where you can create your first realm, register clients, and add users.

For a detailed walkthrough of initial configuration – including creating realms, registering your first application, and testing login – see Getting Started with Keycloak: A Beginner’s Guide to Open Source IAM.

Docker Compose for Development

For a more realistic development setup with a PostgreSQL database:

# docker-compose.yml
version: '3.9'
services:
  postgres:
    image: postgres:16
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: keycloak
    volumes:
      - pgdata:/var/lib/postgresql/data

  keycloak:
    image: quay.io/keycloak/keycloak:26.0
    command: start-dev
    environment:
      KC_DB: postgres
      KC_DB_URL: jdbc:postgresql://postgres:5432/keycloak
      KC_DB_USERNAME: keycloak
      KC_DB_PASSWORD: keycloak
      KC_BOOTSTRAP_ADMIN_USERNAME: admin
      KC_BOOTSTRAP_ADMIN_PASSWORD: admin
    ports:
      - "8080:8080"
    depends_on:
      - postgres

volumes:
  pgdata:

Start the stack with docker compose up -d and you have a Keycloak instance backed by a real database, closer to what you would run in production.

Core Concepts

Understanding Keycloak’s data model is essential before configuring anything. Every object in Keycloak lives within a hierarchy.

Realms

A realm is a top-level tenant in Keycloak. Each realm has its own set of users, clients, roles, identity providers, and authentication flows. Realms are completely isolated from each other – a user in Realm A cannot authenticate against Realm B.

Keycloak ships with a master realm intended for super-admin operations. Best practice is to create separate realms for your applications and never use the master realm for end-user authentication.

Clients

A client represents an application or service that delegates authentication to Keycloak. There are three access types:

  • Public – Browser-based applications (SPAs) that cannot securely store a client secret. Use Authorization Code flow with PKCE.
  • Confidential – Server-side applications that can store a client secret. Use Authorization Code flow or Client Credentials grant.
  • Bearer-only – Backend services that only validate tokens but never initiate a login flow.

Users, Groups, and Roles

Users are individuals who authenticate. Each user has attributes, credentials, and role mappings. Groups organize users hierarchically and can carry default role assignments. Roles come in two flavors:

  • Realm roles – Available across all clients in the realm.
  • Client roles – Scoped to a specific client.

Composite roles let you bundle multiple roles into a single assignable unit. For example, a manager role might include view-reports, edit-users, and approve-requests.

Identity Providers

Identity providers (IdPs) allow users to log in with external credentials. Keycloak supports:

  • Social providers – Google, GitHub, Facebook, Apple, Microsoft, and more.
  • SAML 2.0 providers – Any SAML IdP, including enterprise systems like ADFS or Shibboleth.
  • OIDC providers – Any OpenID Connect-compliant IdP.
  • LDAP/Active Directory – Federated user stores for enterprise directories.

For a deep dive into LDAP integration, including attribute mapping, group synchronization, and Kerberos authentication, see Keycloak User Federation with LDAP and Active Directory.

Authentication Flows

Authentication flows define the steps a user goes through during login. Keycloak ships with default flows for browser login, direct grant (resource owner password), client authentication, and registration. You can customize these or create entirely new flows.

Built-in Flows

The default browser flow performs these steps in order:

  1. Cookie check – If a valid session cookie exists, skip to token issuance.
  2. Identity provider redirect – If configured, redirect to an external IdP.
  3. Username/password form – Collect credentials.
  4. OTP check – If MFA is configured for the user, prompt for a one-time password.

Custom Authentication Flows

Custom flows let you add conditional logic, external system checks, or entirely new authentication mechanisms. Common customizations include:

  • Conditional OTP – Require MFA only when the user logs in from a new device or IP range.
  • Step-up authentication – Require additional verification when accessing sensitive resources.
  • Custom SPI authenticators – Java classes that implement the Authenticator SPI to integrate with proprietary systems like SMS gateways or hardware tokens.

For a hands-on tutorial on building custom authenticators, configuring conditional logic, and deploying custom SPI providers, see Keycloak Custom Authentication Flows: Building Advanced Login Journeys.

Multi-Factor Authentication

Keycloak supports multiple MFA methods out of the box:

  • TOTP – Time-based one-time passwords with Google Authenticator, Authy, or any TOTP-compatible app.
  • WebAuthn – FIDO2/WebAuthn for hardware security keys (YubiKey) and platform authenticators (Touch ID, Windows Hello).
  • Recovery codes – Backup codes for account recovery.

Enable MFA by editing the browser authentication flow in the Admin Console and setting the OTP execution to Required or Conditional.

Social Login

Adding social login takes minutes. Navigate to Identity Providers in the Admin Console, select a provider (e.g., Google), and enter your OAuth client ID and secret. Keycloak handles the redirect flow, token exchange, and user account linking automatically.

Custom Theme Development

The default Keycloak login page is functional but generic. Most organizations need to brand it with their logo, colors, and messaging. Keycloak’s theme system makes this possible without modifying core source code.

Theme Structure

A Keycloak theme consists of templates, stylesheets, images, and a properties file:

themmye-lsco/ogtrltmiheoepnescigma/mosmipneuscglnly.r/u/o.a/pcsgftretoteoso.l.p/mpfe.ntrcgltsises

The theme.properties file specifies the parent theme and any custom styles:

parent=keycloak.v2
import=common/keycloak
styles=css/custom.css

Applying Your Theme

After creating your theme directory, deploy it to Keycloak:

# Copy theme to Keycloak's themes directory
docker cp my-company keycloak:/opt/keycloak/themes/

# Or mount as a volume in Docker Compose
volumes:
  - ./themes/my-company:/opt/keycloak/themes/my-company

Then select your theme in the realm settings under the Themes tab.

For a complete walkthrough covering FreeMarker template customization, CSS overrides, email templates, and deploying themes as JAR files, see Keycloak Custom Theme Development: Branding Your Login Pages.

Admin REST API

The Admin REST API lets you automate everything you can do in the Admin Console – and more. It is the foundation for infrastructure-as-code approaches to Keycloak management, CI/CD pipeline integrations, and custom admin tooling.

Authenticating with the API

First, obtain an access token using the client credentials grant:

# Get an admin access token
ACCESS_TOKEN=$(curl -s -X POST \
  "http://localhost:8080/realms/master/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=admin-cli" \
  -d "client_secret=YOUR_CLIENT_SECRET" \
  | jq -r '.access_token')

Common API Operations

List all users in a realm:

curl -s -X GET \
  "http://localhost:8080/admin/realms/my-realm/users" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  | jq '.[].username'

Create a new user:

curl -s -X POST \
  "http://localhost:8080/admin/realms/my-realm/users" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "jane.doe",
    "email": "[email protected]",
    "enabled": true,
    "firstName": "Jane",
    "lastName": "Doe",
    "credentials": [{
      "type": "password",
      "value": "temp-password",
      "temporary": true
    }]
  }'

Create a new client:

curl -s -X POST \
  "http://localhost:8080/admin/realms/my-realm/clients" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "clientId": "my-api",
    "protocol": "openid-connect",
    "publicClient": false,
    "serviceAccountsEnabled": true,
    "directAccessGrantsEnabled": false
  }'

For a comprehensive API reference with examples covering realm management, role assignment, group operations, client scope configuration, and bulk user import, see Keycloak Admin REST API: Automating User and Realm Management.

High Availability and Clustering

Running a single Keycloak instance is fine for development, but production workloads demand high availability. Keycloak’s architecture supports clustering natively through Infinispan distributed caches and JGroups node discovery.

Production Architecture

A production Keycloak deployment typically includes:

  • Two or more Keycloak nodes behind a load balancer for redundancy.
  • A shared relational database (PostgreSQL recommended) for persistent data.
  • Infinispan distributed caches for session replication and short-lived data.
  • A reverse proxy / load balancer (NGINX, HAProxy, or a cloud ALB) with sticky sessions for optimal performance.

Minimal Production Configuration

# Start Keycloak in production mode
bin/kc.sh start \
  --hostname=auth.example.com \
  --https-certificate-file=/etc/tls/cert.pem \
  --https-certificate-key-file=/etc/tls/key.pem \
  --db=postgres \
  --db-url=jdbc:postgresql://db.example.com:5432/keycloak \
  --db-username=keycloak \
  --db-password=STRONG_PASSWORD \
  --cache=ispn \
  --cache-stack=tcp

Kubernetes Deployment

For Kubernetes environments, use the official Keycloak Operator or a Helm chart:

# Install the Keycloak Operator
kubectl apply -f https://raw.githubusercontent.com/keycloak/keycloak-k8s-resources/refs/heads/main/kubernetes/keycloaks.k8s.keycloak.org-v1.yml
kubectl apply -f https://raw.githubusercontent.com/keycloak/keycloak-k8s-resources/refs/heads/main/kubernetes/keycloakrealmimports.k8s.keycloak.org-v1.yml

Then create a Keycloak custom resource:

apiVersion: k8s.keycloak.org/v2alpha1
kind: Keycloak
metadata:
  name: my-keycloak
spec:
  instances: 3
  db:
    vendor: postgres
    host: postgres-service
    usernameSecret:
      name: keycloak-db-secret
      key: username
    passwordSecret:
      name: keycloak-db-secret
      key: password
  hostname:
    hostname: auth.example.com
  http:
    tlsSecret: keycloak-tls-secret

For a deep dive into Infinispan cache tuning, JGroups discovery protocols, database connection pooling, session affinity configuration, and monitoring with Prometheus, see Keycloak High Availability: Clustering and Production Deployment.

Security Best Practices

Keycloak is secure by default, but operational security requires deliberate configuration. Follow these practices to harden your deployment.

TLS Everywhere

Never run Keycloak without TLS in production. All traffic between clients, load balancers, and Keycloak nodes must be encrypted:

# Generate a self-signed certificate for development
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem \
  -days 365 -nodes -subj "/CN=auth.example.com"

# Start Keycloak with TLS
bin/kc.sh start \
  --https-certificate-file=cert.pem \
  --https-certificate-key-file=key.pem

Protect the Admin Console

  • Restrict network access – The admin console (/admin) should only be accessible from internal networks or VPN. Use firewall rules or load balancer path-based routing.
  • Use strong admin credentials – Change the default admin password immediately and enforce MFA for all admin accounts.
  • Separate admin and user endpoints – Run admin and public endpoints on different ports or hostnames.

Token Security

  • Short access token lifetimes – Set access token lifespan to 5 minutes or less. Use refresh tokens for long-lived sessions.
  • Rotate signing keys – Periodically rotate RSA/EC keys used to sign tokens. Keycloak supports key rotation through the Admin Console.
  • Audience restriction – Configure the aud claim to restrict which services can accept a token.
  • PKCE for public clients – Always require Proof Key for Code Exchange for SPAs and mobile apps.

Database Security

  • Encrypted connections – Use SSL/TLS for database connections with KC_DB_URL parameters.
  • Least privilege – The Keycloak database user should only have permissions on its own schema.
  • Regular backups – Automate daily database backups with point-in-time recovery enabled.

Brute Force Protection

Keycloak includes built-in brute force detection. Enable it in realm settings to lock accounts after repeated failed login attempts:

  • Max login failures – Lock the account after N consecutive failures (e.g., 5).
  • Wait increment – Increase lockout duration with each subsequent failure.
  • Quick login check – Detect automated attacks by monitoring request frequency.

Keycloak vs Commercial Alternatives

Choosing between Keycloak and commercial IAM platforms depends on your organization’s priorities around cost, operational responsibility, and feature requirements.

Keycloak vs Auth0

Auth0 (now part of Okta) is a developer-friendly, cloud-hosted IAM platform. The key trade-offs:

FactorKeycloakAuth0
CostFree (infrastructure costs only)Per-user pricing, free tier up to 25k MAU
HostingSelf-hosted (full control)Managed SaaS
CustomizationUnlimited (source code access)Extension points and Actions
ComplianceOn-premises for data sovereigntySOC 2, HIPAA (enterprise plan)
Time to MarketLonger (setup + ops required)Faster (managed service)

Auth0 excels when you want to ship fast and let someone else handle infrastructure. Keycloak wins when you need cost predictability at scale or must keep data on-premises. For a detailed feature-by-feature comparison, see Auth0 vs Keycloak: Complete Comparison Guide.

Keycloak vs ForgeRock

ForgeRock (now part of Ping Identity) is an enterprise IAM suite with AM (Access Management), IDM (Identity Management), DS (Directory Services), and IG (Identity Gateway). Compared to Keycloak:

  • Feature breadth – ForgeRock offers a more complete out-of-the-box suite with identity governance, provisioning workflows, and a built-in directory. Keycloak focuses on authentication and authorization, relying on external tools for governance.
  • Support – ForgeRock includes commercial SLAs and professional services. Keycloak has community support plus optional Red Hat SSO (RHBK) subscriptions.
  • Cost – ForgeRock licensing is significantly more expensive, often six figures annually. Keycloak is free.

For a thorough comparison covering deployment models, protocol support, and migration paths, see ForgeRock vs Keycloak: Choosing the Right IAM Solution.

Multi-Platform Comparison

If you are evaluating multiple platforms simultaneously, our Comparing ForgeRock, Ping, Auth0, and Keycloak: A Practical Guide breaks down the strengths and weaknesses of each across categories like scalability, developer experience, enterprise features, and total cost of ownership.

When to Choose Keycloak

Keycloak is the right choice when:

  • Budget is constrained – No per-user fees means costs scale with infrastructure, not user count.
  • Data sovereignty matters – On-premises or private cloud deployment keeps data under your control.
  • Customization is critical – Full source code access and SPI extensibility allow unlimited customization.
  • You have DevOps expertise – Your team can manage Kubernetes, databases, and monitoring.
  • Vendor independence is a priority – CNCF governance ensures no single vendor controls the project’s direction.

Migration Guide

Keycloak evolves rapidly, with major releases bringing new features and occasional breaking changes. Planning your upgrade path is critical to avoid downtime.

Upgrading Major Versions

Keycloak supports sequential upgrades only. You cannot skip major versions – for example, upgrading from 21 to 26 requires stepping through 21 to 22 to 23 to 24 to 25 to 26. Each step applies incremental database schema changes via Liquibase.

The general upgrade process:

  1. Back up your database before starting any upgrade.
  2. Read the migration guide for each version you are traversing.
  3. Test in a staging environment that mirrors production.
  4. Upgrade the binary (replace the Keycloak distribution or update the container image tag).
  5. Start Keycloak – it automatically applies pending database migrations on first boot.
  6. Validate – Test login flows, check admin console access, verify token issuance.
# Back up PostgreSQL before upgrade
pg_dump -Fc keycloak > keycloak-pre-upgrade-$(date +%Y%m%d).dump

# Pull the new Keycloak image
docker pull quay.io/keycloak/keycloak:26.0

# Start with the new version (database migrations run automatically)
docker run -d --name keycloak-v26 \
  -p 8080:8080 \
  -e KC_DB=postgres \
  -e KC_DB_URL=jdbc:postgresql://db:5432/keycloak \
  -e KC_DB_USERNAME=keycloak \
  -e KC_DB_PASSWORD=password \
  quay.io/keycloak/keycloak:26.0 start

Key Breaking Changes in Recent Versions

  • Keycloak 22+ – WildFly distribution removed. Quarkus is the only supported distribution.
  • Keycloak 24 – Deprecated legacy admin REST API paths. The /auth prefix is no longer added by default.
  • Keycloak 25 – Organizations feature introduced (tech preview). Changes to user profile SPI.
  • Keycloak 26 – Cache serialization switched from JBoss Marshalling to Infinispan Protostream. Custom themes must migrate from v1 to v2 base theme.

For a complete version-by-version guide covering database migrations, theme compatibility, SPI changes, and rollback procedures, see Keycloak Upgrade Guide: Migrating to Version 26.

Migrating from Other Platforms

If you are migrating to Keycloak from another IAM platform, the approach depends on your source system:

  • ADFS to Keycloak – The most common enterprise migration. Keycloak handles SAML natively, but WS-Federation applications need to be converted to SAML or OIDC. Active Directory users can be federated via LDAP without a full data migration. See ADFS to Keycloak Migration: Open Source Alternative for a step-by-step guide.
  • ForgeRock to Keycloak – Export users from ForgeRock DS, transform the schema, and import via the Admin REST API. Authentication trees need to be recreated as Keycloak authentication flows.
  • Auth0 to Keycloak – Export users via the Auth0 Management API, import into Keycloak. Auth0 Rules/Actions need to be rewritten as Keycloak authenticators or protocol mappers.

Putting It All Together

Building a production-grade Keycloak deployment involves combining the concepts covered above into a cohesive architecture. Here is a recommended approach:

Phase 1 – Proof of Concept. Start with Docker on your local machine. Create a realm, register a test application, and verify login flows work. Follow the Getting Started guide.

Phase 2 – Customization. Brand your login pages with custom themes. Configure authentication flows for MFA and conditional access. Set up LDAP federation if you have existing directory services.

Phase 3 – Automation. Use the Admin REST API to script realm configuration, user provisioning, and client registration. Store configuration as code in your Git repository.

Phase 4 – Production. Deploy a high-availability cluster with database replication, distributed caching, and monitoring. Implement the security best practices outlined above.

Phase 5 – Ongoing Operations. Establish an upgrade strategy to stay current with security patches and new features. Monitor performance metrics and scale horizontally as your user base grows.

Keycloak is a powerful platform that rewards investment in understanding its architecture. The resources linked throughout this guide provide the depth you need for each phase of your journey.