What Is Keycloak? The Complete Beginner's Guide to Identity and Access Management
A ground-up, no-jargon walkthrough of Keycloak — what it is, how it works internally, how logins actually flow, and why so many companies use it to handle authentication instead of building it themselves.
Imagine you own a shopping mall with fifty different stores. Every store needs to check that the person walking in is who they say they are — maybe to let them into a members-only lounge, or to let staff behind the counter. You have two choices. You could ask every single store to build its own front-door security guard, its own ID-checking system, its own list of trusted members. Or you could hire one professional security company that stands at the mall entrance, checks everyone’s ID once, and then hands every store a signed pass that says “this person is verified, and here is what they’re allowed to do.” Keycloak is that one professional security company, but for software applications instead of shops. It is a single, dedicated system that handles logins, passwords, and permissions so that every other application in your company doesn’t have to build that machinery from scratch.
1What Is Keycloak?
Before diving into architecture and protocols, let’s build a plain-English understanding of what this tool actually is and why it exists.
The Simple Definition
Keycloak is a free, open-source software product that manages Identity and Access Management (IAM) for other applications. In plain terms, it is the piece of software responsible for answering two questions every time someone tries to use an application: “Who are you?” (authentication) and “What are you allowed to do?” (authorization). Instead of every website, mobile app, or internal tool writing its own login page, password database, and permission rules, they all delegate that responsibility to Keycloak.
Think of an airport. You don’t show your passport separately to the airline, the duty-free shop, the lounge, and the boarding gate. You show it once at security, get a boarding pass, and every checkpoint after that simply looks at your boarding pass instead of re-verifying your whole identity from scratch. Keycloak plays the role of that airport security desk for software systems — check the person once, issue a trusted “pass” (called a token), and let every other application simply trust that pass.
Why It Exists
Building login systems is deceptively hard. A “simple” login page actually needs to handle password hashing, password reset flows, email verification, protection against brute-force attacks, multi-factor authentication, session expiry, and much more. Doing this correctly, and keeping it secure over time, is a specialized job. Keycloak was created by Red Bull Media House engineer Bill Burke around 2013, and was later donated to Red Hat, which continues to sponsor it as an open-source project. It exists so that development teams can stop reinventing login systems and instead plug into a battle-tested, standards-based one.
Authentication
Proving who you are — usually with a username and password, or a fingerprint, or an OTP code.
Authorization
Deciding what an already-verified person is allowed to see or do, such as “can edit invoices” or “can view reports only.”
Identity Provider (IdP)
The system responsible for verifying identity and issuing proof of that verification. Keycloak acts as an Identity Provider.
Single Sign-On (SSO)
Logging in once and being automatically recognized by every other connected application, without logging in again.
Keycloak isn’t a library you embed inside your app’s code. It’s a separate, standalone server that your applications talk to over standard web requests. Your application never sees or stores raw passwords — it only ever receives a token from Keycloak confirming who the user is.
2Why Companies Need a Dedicated Identity System
To appreciate what Keycloak solves, it helps to see the mess it prevents.
Picture a company that has grown organically over ten years. It now has an internal HR portal, a customer-facing mobile app, an admin dashboard, a partner API, and a support ticketing tool — five separate systems, each built by a different team, possibly in a different programming language. Without a shared identity system, each of these five systems ends up building its own login screen, its own password storage table, and its own “forgot password” email flow. This creates several serious problems.
Problems Without Centralized IAM
- Five different password databases, each a potential security leak
- Users forced to remember five different passwords
- No way to instantly revoke access everywhere when an employee leaves
- Every team re-implements password hashing, MFA, and reset flows — badly, most likely
- No consistent audit trail of who logged in where and when
What a Centralized IAM Like Keycloak Fixes
- One password store, professionally secured and monitored
- One login, shared across all five systems (Single Sign-On)
- Disable one account in Keycloak — access to all five systems disappears instantly
- Security features like MFA and brute-force protection are built once, used everywhere
- One central login and audit log for every application
It’s like a university that issues one student ID card instead of making every building — the library, the gym, the cafeteria, the labs — check your identity in its own unique way. Lose access to the university (you graduate or are expelled) and that one card stops working everywhere at once, rather than someone having to manually revoke five separate accounts.
This pattern — one system responsible for identity, many applications trusting it — is so common that it has a formal name in software architecture: centralized authentication. Keycloak is one of the most widely adopted open-source tools for implementing it, alongside commercial alternatives like Okta, Auth0, Microsoft Entra ID, and Ping Identity.
3Core Building Blocks: Realms, Clients, Users, and Roles
Keycloak organizes everything around four core concepts. Understanding these four unlocks almost everything else.
Realm
A completely isolated “container” of users, applications, and settings. Think of it as a separate company or tenant inside the same Keycloak server.
Client
Any application that wants to use Keycloak for login — a website, mobile app, or backend API is registered as a “client.”
User
A person (or sometimes a service) whose identity Keycloak manages, including their password, email, and profile details.
Role
A label describing what a user is permitted to do, such as “admin,” “editor,” or “viewer,” which applications use to control access.
Realms: The Isolation Boundary
A realm is the most important concept to understand first. It is a completely self-contained world with its own users, its own login page appearance, its own password rules, and its own set of registered applications. A single Keycloak server can host many realms, and none of them can see or interfere with each other. A company might create one realm for its own employees and a completely separate realm for its external customers, because employees and customers need different password policies, different login pages, and different sets of applications.
A realm is like a separate floor in an office building, each with its own reception desk, its own access cards, and its own visitor rules. The IT department in the basement runs the whole building’s electrical system (the Keycloak server), but each floor (realm) is managed as if it were an entirely independent company.
Clients: The Applications That Trust Keycloak
A client is any piece of software that hands off its login duties to Keycloak. This could be a public-facing website, a native mobile app, a single-page React application, or a backend service that needs to verify who is calling it. Every client is registered inside a realm and given a unique identifier so Keycloak knows which application is asking for a login.
Public Clients
Used by front-end applications like single-page apps or mobile apps that run on a user’s device and cannot safely keep a secret, since anyone could inspect the app’s code.
Confidential Clients
Used by backend servers that can safely store a secret credential, allowing for a more tightly controlled and secure conversation with Keycloak.
Users and Roles
Users are the actual people (or automated services) that log in. Each user has attributes like username, email, and password, plus optional custom fields like department or employee ID. Roles describe permissions. A role isn’t tied to a specific screen or button by itself — it’s simply a label like billing-admin that the application itself checks for before allowing an action. Keycloak also supports groups, which bundle multiple users together so roles can be assigned to the whole group at once rather than one user at a time.
Keycloak does not decide what happens when a role is present — it only tells the application “this user has the billing-admin role.” The application itself is still responsible for checking that role before showing the billing screen or blocking access. Keycloak is the source of truth for identity and roles, not the enforcer of every button and screen.
4Architecture: How Keycloak Is Put Together
Now that the vocabulary is clear, let’s look at the physical and logical pieces that make up a running Keycloak deployment.
flowchart TB
U[User's Browser or App] -->|1 Login Request| KC[Keycloak Server]
KC -->|2 Reads and Writes| DB[(Database)]
KC -->|3 Issues Tokens| U
U -->|4 Sends Token| APP[Your Application / API]
APP -->|5 Validates Token| KC
The Keycloak Server
At the center sits the Keycloak server itself, a Java application (built on the Quarkus framework in modern versions) that exposes web endpoints for logging in, issuing tokens, managing users, and administering the whole system. It ships with a built-in Admin Console, a web-based dashboard where administrators create realms, register clients, manage users, and configure security policies — all without writing code.
The Database
Keycloak needs persistent storage to remember users, realms, clients, roles, and sessions across restarts. In production, this is almost always an external relational database such as PostgreSQL, MySQL, or Microsoft SQL Server. The database is Keycloak’s memory — if it’s lost, every user, password, and configuration is lost with it, which is why backing it up is treated as a critical operational task.
The Login Pages (Themes)
When a user is redirected to log in, they land on a page actually hosted and rendered by Keycloak itself, not by your application. This page can be restyled using Keycloak’s theming system so it matches your company’s branding, while the underlying security logic stays exactly the same.
Your Applications (Clients)
Surrounding the Keycloak server are all the applications that trust it — websites, mobile apps, and backend APIs. None of these applications store passwords themselves. They redirect users to Keycloak for login and then receive a signed token proving that login succeeded.
5Tokens: The “Passes” Keycloak Hands Out
Tokens are the single most important concept for understanding how Keycloak actually works day to day.
Once a user proves who they are, Keycloak doesn’t ask your application to remember a password or re-check credentials on every request. Instead, it issues digitally signed pieces of text called tokens, which act like a stamped, tamper-proof pass. Keycloak uses an open standard called OpenID Connect (OIDC), which itself is built on top of an authorization standard called OAuth 2.0, to issue three main types of tokens.
Access Token
A short-lived pass (often valid for just a few minutes) that your application sends to prove the user is logged in and to check their roles.
Refresh Token
A longer-lived credential used to silently get a brand-new access token once the old one expires, without forcing the user to log in again.
ID Token
A token specifically describing who the user is — name, email, and other profile details — used by the application to personalize the experience.
An access token is like a concert wristband — small, quick to check at any gate, and it expires after the event. A refresh token is like the ticket stub you keep in your pocket, which you can exchange at the booth for a fresh wristband if yours runs out before the concert ends, without buying a whole new ticket.
Why Tokens Are Signed, Not Encrypted
Most Keycloak tokens are formatted as a JSON Web Token (JWT). A JWT is digitally signed using cryptographic keys that only Keycloak holds, which means any application can verify the token is authentic and untampered just by checking the signature — without needing to call Keycloak back every single time. This is what makes token-based systems fast: verification can often happen locally, inside the application, in milliseconds.
Access tokens are deliberately short-lived — often five to fifteen minutes — so that if one is ever stolen, the window during which it can be misused is small. The refresh token keeps the user experience seamless despite these short expiries by quietly fetching new access tokens in the background.
6How a Login Actually Flows, Step by Step
Let’s trace exactly what happens, moment by moment, when a user clicks “Log In” on an application that uses Keycloak.
User clicks “Log In”
The application redirects the user’s browser away from itself and over to the Keycloak server’s login page — the application never sees the password field at all.
User enters credentials on Keycloak’s page
Keycloak checks the username and password against its own database, and may also ask for a second factor such as an OTP code if multi-factor authentication is enabled.
Keycloak redirects back with a temporary code
After a successful login, Keycloak sends the browser back to the application with a short-lived, one-time authorization code attached to the URL.
Application exchanges the code for tokens
Behind the scenes, the application’s backend sends that code straight to Keycloak and receives back an access token, a refresh token, and an ID token.
Application uses the access token
The application now knows who the user is and what roles they hold, and attaches the access token to every subsequent request it makes to protected APIs.
sequenceDiagram
participant Browser
participant App as Application
participant KC as Keycloak
Browser->>App: Click "Log In"
App->>Browser: Redirect to Keycloak
Browser->>KC: Enter username & password
KC->>Browser: Redirect back with auth code
Browser->>App: Deliver auth code
App->>KC: Exchange code for tokens
KC->>App: Access token, refresh token, ID token
App->>Browser: Logged-in page shown
This pattern is called the Authorization Code Flow, and it’s the recommended flow for almost all modern applications because the password itself is only ever typed into Keycloak’s own page, never handled or stored by your application’s code. Older or simpler flows exist for special cases like machine-to-machine communication, but the Authorization Code Flow is the default for anything involving a human user.
7Sessions and Single Sign-On in Practice
Tokens explain a single login — but how does Keycloak let a user move between five different applications without logging in five separate times?
When a user logs in successfully, Keycloak doesn’t just issue tokens to that one application — it also creates a session on its own server and places a special cookie in the user’s browser. The next time the user visits a different application that also trusts the same Keycloak realm, the browser is redirected to Keycloak as usual, but this time Keycloak notices the session cookie, recognizes the user is already logged in, and skips the login form entirely, silently issuing fresh tokens for the new application.
It’s exactly like a hotel key card that also happens to unlock the gym, the pool area, and the parking garage. You only checked in once at the front desk (Keycloak), but the card (the session cookie) keeps proving your identity everywhere else on the property without another check-in.
This is also what makes centralized logout possible. Because Keycloak knows every application the user has silently logged into during that session, a single “Log Out” action can notify all of them at once, instead of the user having to log out of each application individually — a feature usually called Single Logout (SLO).
Beginners sometimes assume logging out of one application automatically logs the user out everywhere by default. Single Logout has to be explicitly configured on each client, and each application must implement the logic to react to Keycloak’s logout notification — it doesn’t happen automatically just because Keycloak is in use.
8Advantages, Disadvantages, and Trade-offs
Like every technology choice, adopting Keycloak comes with real benefits and real costs. Understanding both helps you decide when it’s the right fit.
Advantages
- Completely free and open-source, with no per-user licensing fees
- Supports industry-standard protocols (OIDC, OAuth 2.0, SAML), avoiding vendor lock-in
- Battle-tested by thousands of companies, backed by Red Hat
- Rich built-in features: MFA, social login, brute-force detection, password policies
- Highly customizable login pages (themes) and extensible via plugins
- Self-hosted, so sensitive user data never leaves your own infrastructure
Disadvantages / Trade-offs
- You are responsible for hosting, scaling, patching, and securing it yourself
- Steeper learning curve than plug-and-play commercial services
- Requires a properly managed, backed-up database as a hard dependency
- Admin console and configuration options can feel overwhelming to newcomers
- Version upgrades sometimes require careful migration planning
The general rule of thumb: Keycloak tends to be an excellent fit for organizations with the engineering capacity to run and maintain their own infrastructure, who want full control and no per-user pricing. Managed commercial alternatives like Auth0 or Okta trade away that control and cost predictability in exchange for someone else handling the operational burden.
9Security Features Inside Keycloak
Because Keycloak’s entire purpose is security, it’s worth understanding the protective layers it provides out of the box.
Multi-Factor Authentication
Adds a second proof of identity, such as an OTP app or WebAuthn hardware key, on top of the password.
Brute-Force Detection
Automatically locks or slows down an account after repeated failed login attempts, blocking password-guessing attacks.
Password Policies
Enforces rules like minimum length, complexity, expiry, and blocking reuse of recent passwords.
Token Signing
Every token is cryptographically signed with keys unique to the realm, so forged tokens are mathematically detectable.
Fine-Grained Permissions
Beyond simple roles, Keycloak’s Authorization Services can enforce detailed, resource-level access policies.
Identity Brokering
Lets users log in via external providers like Google, Facebook, or a company’s existing corporate directory.
One especially important integration is with LDAP and Active Directory, the systems many large organizations already use to manage employee accounts. Keycloak can connect directly to these existing directories, letting employees log into modern applications using the exact same corporate username and password they already have, without duplicating that data into a second system.
10Monitoring, Logging, and Metrics
Once Keycloak is running in production, watching its health becomes just as important as configuring it correctly in the first place.
Keycloak produces detailed event logs for security-relevant actions — logins, failed logins, password changes, token refreshes, and administrative changes like creating a new user or role. These logs form an audit trail that security teams rely on to investigate suspicious activity or satisfy compliance requirements like SOC 2 or ISO 27001.
| What to Monitor | Why It Matters |
|---|---|
| Failed login rate | A sudden spike often signals a brute-force or credential-stuffing attack in progress |
| Token issuance rate | Unusually high volumes can indicate misuse or a misbehaving application client |
| Database connection health | Keycloak cannot function at all if it loses its database connection |
| Response latency | Slow login pages directly translate into slow, frustrating logins for every connected app |
| Admin actions log | Tracks who created, modified, or deleted realms, clients, and users |
In production deployments, teams commonly export Keycloak’s metrics to monitoring stacks like Prometheus and Grafana, giving them dashboards and alerts for things like CPU usage, memory, request latency, and login failure spikes — the same way they’d monitor any other critical piece of infrastructure.
Because Keycloak sits directly in the critical path of every login across every connected application, teams typically treat its uptime and monitoring with the same seriousness as their main database — if Keycloak goes down, users across the entire company can be locked out of everything at once.
11Design Patterns and Anti-Patterns
Years of real-world Keycloak deployments have surfaced clear patterns worth following and pitfalls worth avoiding.
Pattern: One Realm Per Trust Boundary
Successful deployments typically create a separate realm for each genuinely distinct population of users — for example, internal employees versus external customers — rather than mixing them in one realm and relying only on roles to separate them.
Pattern: Confidential Clients for Backend Services
Server-side applications that can safely hold a secret should always be registered as confidential clients, reserving the less-trusted “public client” type for browser and mobile apps that cannot keep secrets hidden.
Pattern: Short-Lived Access Tokens, Longer Refresh Tokens
Keeping access tokens short-lived while allowing a longer refresh token window balances security against user convenience, minimizing the damage window if a token is ever stolen.
Problem
An application stores the user’s raw password locally so it can “auto-login” later, instead of relying on the refresh token Keycloak already provides for this purpose.
Why It’s Harmful
It reintroduces exactly the risk Keycloak was adopted to eliminate — a password sitting in application storage, outside Keycloak’s protection, and a much larger attack surface if that storage is ever breached.
Correct Approach
Let Keycloak’s refresh token mechanism handle staying logged in, and never let application code see, log, or store the user’s actual password.
Problem
Treating every application in the company as a “public client” for simplicity, even backend services that could safely hold a secret.
Why It’s Harmful
Public clients receive weaker security guarantees by design, since they’re assumed to be untrustworthy environments — using that setting unnecessarily widens the potential attack surface for services that didn’t need it.
Correct Approach
Classify each client honestly based on whether it can protect a secret, and configure confidential clients wherever that’s genuinely possible.
12Best Practices and Common Mistakes
Beyond high-level patterns, here are concrete, actionable habits that separate smooth Keycloak deployments from painful ones.
Never Reuse the Master Realm
Keep the built-in “master” realm strictly for Keycloak’s own admin accounts, and create dedicated realms for actual applications and users.
Back Up the Database Religiously
Since the database holds every user, password hash, and configuration, treat its backups with the same seriousness as your most critical production data.
Run Keycloak Behind HTTPS Always
Because tokens and credentials flow through Keycloak constantly, running it without encryption in transit defeats the purpose of its entire security model.
Test Upgrades in Staging First
Major version upgrades can change default behaviors; testing in a staging environment avoids surprising every connected application at once.
Setting overly long access token lifetimes “to reduce login friction” is a frequent beginner mistake. It quietly weakens security by extending the window during which a stolen token remains usable, when the refresh token mechanism already solves the friction problem safely.
13Real-World and Industry Examples
Keycloak isn’t a theoretical tool — it’s deployed at genuine scale across many kinds of organizations.
Enterprise Internal Tools
Large enterprises often use Keycloak to give employees Single Sign-On across dozens of internal dashboards, HR systems, and developer tools, connected to their existing Active Directory.
SaaS Products with Multi-Tenant Customers
Software-as-a-Service companies use Keycloak’s realm-per-tenant capability to give each business customer their own isolated login experience and user base within a single Keycloak deployment.
Government and Public Sector Portals
Because it’s open-source, self-hostable, and free from vendor lock-in, Keycloak is a popular choice for government digital services that must keep citizen data within national infrastructure.
API Platforms and Microservices
In microservice architectures, Keycloak frequently secures dozens of internal APIs at once, with each service independently validating the same signed access tokens without needing to call Keycloak on every request.
Its adoption spans banking, healthcare, e-commerce, telecom, and education sectors — essentially any industry where “who is this user, and what are they allowed to do” is a question asked thousands of times per second.
14Frequently Asked Questions
Yes. Keycloak is fully open-source under the Apache 2.0 license, with no per-user or per-login fees. You only pay for the infrastructure you host it on.
Not to get started, but running it safely in production benefits greatly from understanding the concepts in this guide — realms, tokens, and client types especially.
Not usually — most companies keep Active Directory as their source of employee records and connect Keycloak to it, rather than replacing it, so Keycloak acts as a bridge to modern web protocols.
Both are protocols Keycloak supports for authentication. OpenID Connect (OIDC) is newer, lighter-weight, and built for modern web and mobile apps, while SAML is older and still common in enterprise software.
No. Passwords are stored as cryptographic hashes using strong hashing algorithms, meaning even Keycloak’s own database never holds a readable copy of anyone’s password.
Yes, with proper infrastructure. Keycloak can run in a clustered, horizontally scaled configuration backed by a robust database to support very large user bases.
Any application relying on it for login will be unable to authenticate new sessions, which is why production deployments run Keycloak redundantly across multiple instances to avoid a single point of failure.
15Summary and Key Takeaways
Keycloak solves a problem almost every growing software company eventually faces: managing logins, passwords, and permissions consistently and securely across many different applications. Rather than every team reinventing authentication, Keycloak centralizes it into one trusted, standards-based server that issues signed tokens, enables Single Sign-On, and enforces strong security practices like MFA and brute-force protection out of the box. Understanding its core building blocks — realms, clients, users, roles, and tokens — along with the login flow that ties them together, gives you a solid foundation for working with, deploying, or simply discussing modern identity and access management systems.
Key Takeaways
- Keycloak is a dedicated Identity and Access Management server — it centralizes login and permissions so applications don’t have to build their own.
- Realms are isolated tenants — each realm has its own users, clients, and settings, completely separate from other realms on the same server.
- Clients are the applications that trust Keycloak, registered as either public (browser/mobile) or confidential (backend) depending on whether they can safely hold a secret.
- Tokens are signed digital passes — access tokens for quick verification, refresh tokens for staying logged in, and ID tokens for user profile details.
- The Authorization Code Flow is the standard, secure login sequence, ensuring passwords are only ever typed into Keycloak’s own page.
- Sessions and cookies power Single Sign-On, letting users move between connected applications without repeated logins.
- Operating Keycloak well means owning its infrastructure — backups, HTTPS, monitoring, and careful upgrades are the trade-off for its flexibility and zero licensing cost.