Two-Factor Authentication (OTP) in Keycloak
A complete, zero-prior-knowledge guide to how Keycloak turns a simple username and password into a two-step lock — the theory behind One-Time Passwords, how Keycloak wires it into every login, and how real companies use it to stop account takeovers.
Imagine a bank vault that opens with a single key. Anyone who copies that key — by watching you use it, by tricking you into handing it over, or by finding it lying around — can walk in and take everything. That is exactly what a website protected only by a password looks like to an attacker. Passwords get guessed, reused across a dozen sites, phished through fake login pages, and leaked in bulk when some other company gets hacked. Two-Factor Authentication, often shortened to 2FA, is the second lock on that vault: even if someone steals your key, they still cannot get in without a second, completely different kind of proof. This article explains, from the ground up, how Keycloak — one of the most widely used open-source identity platforms in the world — implements one particular and extremely popular form of that second lock: the One-Time Password, or OTP.
Foundations
Core Concepts
Before we can talk about how Keycloak implements OTP, we need to agree on what each of these words actually means, one at a time.
What is Keycloak?
Keycloak is a free, open-source software product whose entire job is to answer two questions on behalf of other applications: “who are you?” and “what are you allowed to do?” These two questions have formal names — authentication (proving who you are) and authorization (deciding what you can access). Rather than every company building its own login page, password database, and security logic from scratch, they install Keycloak once and point all their applications at it. Keycloak then becomes the single front door for every login across the organization, a pattern known as an Identity Provider, or IdP.
Think of Keycloak like the security desk in a large office building that houses many different companies. Instead of each company hiring its own security guard and issuing its own badges, everyone shares one front desk. You show your ID once at the ground floor, and that single check lets you move between the offices of Company A, Company B, and Company C without proving your identity all over again at each door. Keycloak is that shared front desk for software applications.
What is Two-Factor Authentication?
Authentication factors are traditionally grouped into three categories: something you know (a password, a PIN), something you have (a phone, a hardware key, a smart card), and something you are (a fingerprint, a face scan). A system that checks only one of these categories is called single-factor authentication. Two-Factor Authentication requires proof from two different categories before granting access — typically something you know (your password) combined with something you have (your phone, which can generate or receive a code). The key word is different categories. Asking for a password and then a security question is still, in spirit, two things you know, and is much weaker than combining a password with a physical device.
What is an OTP (One-Time Password)?
An OTP is a short numeric code — usually six or eight digits — that is valid for only a single use, or for a very short window of time, typically thirty seconds. Unlike your regular password, which stays the same until you change it, a new OTP is generated fresh for every login attempt. Because it expires almost immediately and cannot be reused, an attacker who intercepts one OTP gains almost nothing: by the time they try to use it, it has usually already expired or already been consumed.
Password
A secret string you memorize. Reusable, guessable, phishable, and often leaked in data breaches.
OTP-generating device
Your phone running an authenticator app, holding a secret key that no one else possesses.
Biometrics (not covered here)
Fingerprint or face recognition. A different factor entirely, handled by different Keycloak features like WebAuthn.
2FA login
Password proves knowledge, OTP proves possession. Together, they are far harder to defeat than either alone.
Keycloak supports OTP as a built-in, first-class authentication method. No plugins, no third-party servers, and no custom code are required to turn it on for a realm — it is baked directly into the product because it is one of the oldest and most trusted forms of 2FA in the industry.
Structure
Architecture & Components
Keycloak’s OTP feature is not one single thing — it is several smaller pieces working together. Understanding each piece separately makes the whole system click into place.
Realms — the isolated tenants
Everything in Keycloak lives inside a realm. A realm is a completely isolated space with its own users, its own applications, and its own security rules, including its own OTP settings. A company running Keycloak might have one realm for employees and a separate realm for customers, each with entirely independent 2FA policies. This isolation means turning on OTP for the customer-facing realm has zero effect on the employee realm.
The OTP Policy
Inside every realm, an administrator configures an OTP Policy — a small set of rules that decides exactly how the One-Time Passwords for that realm will behave. This policy answers several concrete questions: should codes be based on a moving clock (TOTP) or a counter that increases with every use (HOTP); how many digits should the code have, typically six or eight; which cryptographic hashing algorithm should generate the code, usually SHA1 but optionally the stronger SHA256 or SHA512; how many seconds should each TOTP code remain valid for, most commonly thirty; and how large a “look-ahead window” the server should tolerate for clock drift between the user’s phone and the server.
Authenticator apps
Keycloak does not build its own mobile app. Instead, it relies on the same open standard that every major authenticator app already understands. A user can generate their Keycloak OTP codes using FreeOTP (an open-source app built by the same community behind Keycloak), Google Authenticator, Microsoft Authenticator, or any other TOTP-compatible app they already trust. This is possible because Keycloak follows an open, published algorithm rather than inventing its own proprietary format.
Credentials storage
When a user sets up OTP, Keycloak stores a credential record tied to that user — essentially a securely stored secret key plus metadata about which OTP policy generated it. This credential lives inside Keycloak’s own user database, separate from the password credential, so a user can have a password credential, an OTP credential, and other credential types like WebAuthn security keys all attached to the same account simultaneously.
Authentication flows
Keycloak controls the entire sequence of steps a user goes through when logging in using something called an authentication flow — a visual, configurable pipeline of individual steps such as “enter username and password,” “verify OTP,” or “reset password if required.” Administrators can drag, reorder, and configure these steps in the admin console without writing any code. The default “Browser” flow already includes an OTP step, and each step can be marked as Required, Alternative, Conditional, or Disabled, which is what allows an organization to decide whether OTP is mandatory for everyone, optional, or only triggered under specific conditions.
flowchart TD
A["User's Browser"] --> B["Keycloak Login Page"]
B --> C["Authentication Flow Engine"]
C --> D["Step 1: Username & Password Check"]
D -->|"Password correct"| E["Step 2: OTP Policy Lookup"]
E --> F["Step 3: Prompt for OTP Code"]
F --> G["Authenticator App on User's Phone"]
G -->|"6-digit code"| F
F --> H["Compare code against stored OTP credential"]
H -->|"Match"| I["Issue Login Session / Token"]
H -->|"No match"| J["Deny & Show Error"]
C --- K["Realm Settings: OTP Policy, Credential Store, Flow Config"]
Fig 1 — The core architectural pieces of Keycloak OTP working together during a single login attempt.
Notice that the diagram shows five distinct components — the browser, the flow engine, the realm’s OTP policy, the stored credential, and the user’s authenticator app — none of which is the “one thing” people usually picture when they hear “2FA.” Keycloak’s strength is that it assembles all five into a system an administrator configures through settings screens rather than by writing custom authentication logic.
Mechanics
Internal Working
This is the chapter that answers the question people ask most often: how can a phone that has never talked to Keycloak’s server produce a code the server recognizes as correct?
The shared secret
The trick starts at enrollment. When a user turns on OTP for the first time, Keycloak generates a random secret key — a long string of characters that only that user’s account and that user’s authenticator app will ever know. Keycloak displays this secret as a QR code on screen. The user scans it with their phone’s authenticator app, which silently stores the exact same secret. From that moment on, both sides — Keycloak’s server and the user’s phone — possess an identical, private secret that never travels across the network again.
Picture twins who are separated at birth but given identical secret notebooks full of pre-agreed answers to a never-ending list of trivia questions. Years later, a stranger can ask either twin, “what’s the answer to question 4,829?” and both will independently give the exact same answer — not because they communicated recently, but because they started with the same notebook. Keycloak’s server and your phone are those twins, and the “notebook” is the shared secret key created at enrollment.
TOTP — Time-based One-Time Password
Keycloak’s default OTP mode is TOTP, standardized in an open specification known as RFC 6238. TOTP combines two ingredients: the shared secret, and the current time, rounded down to the nearest thirty-second window. Both Keycloak’s server and the user’s phone independently take the shared secret and the current time window, run them through a well-known cryptographic function called HMAC (Hash-based Message Authentication Code), and truncate the mathematical result down into a friendly six-digit number. Because both sides use the same secret and the same time window, they arrive at the identical six digits without ever exchanging a single message during that thirty-second period. When you type the code into Keycloak’s login page, the server simply recomputes its own version of the code for that same time window and checks whether the two match.
HOTP — the counter-based alternative
Keycloak also supports a second, older mode called HOTP, defined in RFC 4226. Instead of relying on the current time, HOTP relies on a counter that increases by one every time a code is successfully used. The math is nearly identical to TOTP, but the “changing ingredient” is a number that goes up instead of a clock that ticks forward. HOTP is less common today because it is more sensitive to the counters on the server and the device drifting out of sync, but it remains useful in environments like hardware tokens that have no reliable internal clock.
Why the code changes every thirty seconds
The short lifetime is the entire point of the design. If someone shoulder-surfs your screen, intercepts network traffic, or even convinces you to read the code aloud over the phone, the window in which that stolen code is still valid is extremely small — usually well under a minute. Compare this to a stolen password, which often remains valid for months or years until someone changes it.
The look-ahead window and clock drift
Phone clocks are not perfectly synchronized with server clocks; small drift is normal. Keycloak’s OTP policy includes a configurable “look-ahead window,” which tells the server to also accept codes from one or two time windows immediately before or after the current one. This gives a small amount of tolerance for clock drift without meaningfully weakening security, since the acceptable window is still measured in tens of seconds, not minutes or hours.
Because TOTP is a published, non-proprietary standard, Keycloak is compatible with essentially every mainstream authenticator app on the market. A user is never locked into a single vendor’s app — they simply need an app that speaks the same RFC 6238 standard Keycloak speaks.
OTP touches a user’s account at two very different moments: the one-time setup, called enrollment, and every subsequent login. Both flows are worth walking through step by step.
Enrollment: setting up OTP for the first time
Trigger the Configure OTP required action
An administrator either forces this for all users, or a user opts in voluntarily from their account settings. Keycloak marks the account with a “Configure OTP” required action.
Server generates a fresh secret
Keycloak creates a cryptographically random secret unique to that user and displays it as both a scannable QR code and a plain-text backup string.
User scans the QR code
The authenticator app on the phone reads the secret and immediately begins generating six-digit codes that refresh every thirty seconds.
User confirms with one code
To prove the scan worked correctly, the user types the current code shown on their phone back into Keycloak. This single confirmation step prevents a broken or mistyped secret from being saved silently.
Credential is saved
Keycloak stores the OTP credential permanently against the user’s account. The required action is cleared, and the account is now protected by two factors going forward.
Login: using OTP on every subsequent sign-in
Username and password step
The user enters their normal credentials. Keycloak validates them against the stored password hash exactly as it would in a single-factor login.
Flow engine checks for an OTP credential
If the account has an OTP credential attached and the authentication flow marks OTP as required (or the conditions for a conditional OTP step are met), Keycloak moves to the next step instead of finishing the login.
User is prompted for a code
The user opens their authenticator app, reads the currently displayed six-digit number, and types it into Keycloak’s second-step login screen.
Server recomputes and compares
Keycloak independently calculates what the correct code should be for the current time window, using the stored secret, and compares it against what the user typed, allowing for the configured look-ahead window.
Session is issued or login is denied
On a match, Keycloak issues the normal login session and security tokens exactly as it would for any successful login. On a mismatch, the attempt is rejected and, depending on configuration, may count toward brute-force lockout thresholds.
Weighing the Choice
Advantages, Disadvantages & Trade-offs
No security control is free. OTP dramatically raises the bar for attackers, but it also introduces real friction and real failure modes that a well-run system must plan for.
Advantages
- Stops the overwhelming majority of automated credential-stuffing and password-reuse attacks, since a leaked password alone is no longer enough
- Works offline — the authenticator app needs no internet connection or SMS network to generate a valid code
- Based on an open, standardized algorithm, so it is not tied to any single vendor or paid service
- Built directly into Keycloak, requiring no external OTP delivery service, SMS gateway, or additional infrastructure cost
- Codes expire in seconds, drastically shrinking the window during which a stolen code is useful
Disadvantages & Trade-offs
- Adds a genuine extra step to every login, which some users experience as friction, especially on shared or frequently used devices
- A lost, factory-reset, or stolen phone can lock a legitimate user out of their own account unless a recovery process exists
- Vulnerable to real-time phishing, where an attacker’s fake login page relays the OTP to the real site within the thirty-second window
- Requires clocks to stay reasonably synchronized between server and device, which the look-ahead window only partially compensates for
- Does not protect against malware that has already taken over the user’s authenticated session after a successful login
Why organizations accept the trade-off anyway
Security decisions almost never eliminate risk; they shift the balance of probability. Every disadvantage above is either rare, mitigatable through good process, or dramatically outweighed by the class of attacks it blocks. A stolen password used to mean instant, silent account takeover. With OTP correctly enforced, that same stolen password becomes almost worthless to an attacker who does not also physically possess the victim’s phone. For most organizations handling anything of real value — money, health records, source code, customer data — that trade is an easy one to make.
Defense
Security
Turning on OTP is not the end of the security conversation — it is the beginning of a new, narrower one about the specific ways OTP itself can still be attacked or misused.
Real-time phishing (the “man-in-the-middle” relay)
Because OTP codes are typed by a human into a web form, an attacker can build a convincing fake copy of the login page, capture the password and the OTP as the victim types them, and instantly relay both to the real Keycloak login page before the code expires. This is the single most important weakness of any OTP scheme, including Keycloak’s. It is not a flaw unique to Keycloak — it applies to virtually every OTP-based system in the industry — but it is essential to understand, because it explains why some organizations eventually move toward phishing-resistant methods like WebAuthn security keys in addition to, or instead of, OTP.
Many people assume OTP makes phishing impossible. It does not. OTP makes stolen passwords worthless on their own, but a sufficiently convincing, real-time phishing site can still capture and relay both factors together. OTP raises the cost and sophistication required to attack an account; it does not remove the risk entirely.
Brute-force protection
A six-digit code has one million possible combinations, which sounds like a lot but is small enough to guess quickly with automated tools if an attacker is allowed unlimited attempts. Keycloak’s built-in brute-force detection feature closes this gap by tracking failed OTP attempts per user and temporarily locking the account after a configurable number of consecutive failures, making blind guessing impractical.
Protecting the secret at rest
The shared secret generated during enrollment is one of the most sensitive pieces of data in the entire system — anyone who obtains it can generate valid codes forever, without ever touching the user’s phone again. Keycloak stores this secret inside its credential store, and production deployments are expected to encrypt the underlying database and restrict administrative access tightly, since a database breach that exposes raw OTP secrets is functionally equivalent to handing every affected user’s second factor to the attacker.
Recovery and backup codes
Because losing a phone means losing the ability to generate OTP codes, most production deployments pair OTP with a recovery mechanism — commonly a set of one-time-use backup codes generated at enrollment and stored somewhere safe by the user, or an administrator-assisted reset process where a verified administrator manually removes the OTP credential after confirming the user’s identity through another channel. Without a thought-out recovery path, OTP enforcement can turn a lost phone into a full account lockout.
Combining OTP with conditional and step-up flows
Keycloak’s flow engine allows OTP to be applied conditionally rather than universally — for example, only requiring the second factor when a user logs in from an unrecognized device or location, or only requiring it again before a particularly sensitive action like changing a password or transferring money, a pattern known as step-up authentication. This lets an organization balance security against user friction rather than treating every login as equally risky.
Visibility
Monitoring, Logging & Metrics
A security control that no one is watching is only half a control. Keycloak gives administrators visibility into exactly how OTP is being used and abused across the realm.
The built-in Events system
Keycloak ships with an events subsystem that records security-relevant actions, including OTP-specific ones such as when a user successfully sets up OTP, when a login succeeds after an OTP challenge, and when an OTP attempt fails. Administrators can view these events directly in the admin console or export them to an external logging and monitoring system for long-term analysis.
What administrators should actually watch for
Raw event logs become genuinely useful once they are turned into patterns. A sudden spike in OTP login failures for a single account can indicate an attacker attempting to guess codes, or brute-force protection quietly doing its job. A cluster of “Configure OTP” resets happening for many different accounts in a short window can indicate a compromised administrator account being used to strip away second factors across the organization. Repeated OTP failures immediately followed by a successful login from an unusual IP address or geography can suggest a successful real-time phishing relay attack in progress, even though the login technically “succeeded.”
Exporting events for long-term visibility
Because Keycloak’s built-in event storage is not designed as a permanent archive, most production deployments forward events to an external system — a centralized log aggregator or a security information and event management platform — so that patterns can be correlated across weeks or months, alerts can be configured automatically, and compliance auditors can review historical evidence that 2FA was actually enforced and functioning, not merely configured.
Shape
Design Patterns & Anti-patterns
How an organization structures its Keycloak realms and flows around OTP has a bigger impact on real-world security than the OTP algorithm itself. A few patterns show up repeatedly across successful — and unsuccessful — deployments.
Pattern: Conditional OTP based on risk
Rather than forcing every single login through an OTP prompt, mature deployments configure the authentication flow to trigger OTP only when a risk signal is present — a new device, an unusual IP range, or a sensitive application being accessed. Routine, low-risk logins from a known device stay fast, while risky ones get the extra scrutiny they deserve.
Pattern: Step-up authentication for sensitive actions
Some deployments treat the initial login as only a baseline. Before a particularly consequential action — deleting an account, changing banking details, approving a large payment — the application asks Keycloak to force a fresh OTP challenge again, even if the user already has an active session. This ensures a hijacked session alone is not enough to perform the most damaging actions.
Pattern: Multiple factor options, one policy
Rather than mandating OTP specifically, some organizations configure the flow so users can satisfy the second factor with either OTP or a WebAuthn security key, marking both as “Alternative” steps. Users who own a phishing-resistant hardware key can use it, while everyone else still gets meaningful protection through OTP.
Anti-pattern: Treating OTP as a complete security solution
A frequent mistake is enabling OTP and then assuming the account is now “unhackable.” OTP raises the cost of an attack significantly, but it does not defend against session hijacking after login, malware on the user’s own device, or a well-executed real-time phishing relay. Teams that stop thinking about security the moment OTP is switched on leave real gaps unaddressed.
Anti-pattern: No recovery path
Enforcing OTP realm-wide without first building a tested account-recovery process is one of the most common operational failures. The very first time a real user loses their phone, the organization discovers — under pressure, during a live incident — that there is no safe way to let them back into their own account without either weakening security ad hoc or leaving the user permanently locked out.
Situation
An organization enables OTP as a Required step for all users in a single afternoon, with no advance communication and no backup-code process in place.
Consequence
Within hours, the support queue fills with users locked out after losing or replacing phones, and administrators are forced to manually reset OTP credentials one at a time without a verified identity-check process, quietly reopening the exact account-takeover risk the rollout was meant to close.
Better Approach
Roll out OTP gradually as Alternative or Conditional first, generate and communicate backup codes at enrollment, and define a documented, identity-verified recovery procedure before making OTP mandatory realm-wide.
Getting It Right
Best Practices & Common Mistakes
The difference between an OTP rollout that quietly strengthens an organization and one that generates endless support tickets almost always comes down to a handful of practical decisions.
Generate backup codes at enrollment
Give every user a small set of one-time recovery codes the moment they set up OTP, stored somewhere safe, so a lost phone does not immediately mean a lost account.
Set a sensible look-ahead window
Allow a small tolerance for clock drift, but keep it tight enough that it does not meaningfully widen the attack window for a stolen code.
Roll out gradually
Start with OTP as optional or conditional, gather feedback and support data, and only make it mandatory once the recovery process has proven itself under real usage.
Pair with brute-force protection
Always enable account lockout after repeated failed OTP attempts; the six-digit code space is not large enough to rely on the algorithm alone.
Storing secrets unencrypted
Leaving the underlying database that holds OTP secrets unencrypted turns a single breach into a mass second-factor compromise.
No identity check on manual resets
Letting support staff disable a user’s OTP credential on request alone, without verifying identity, recreates exactly the account-takeover path OTP was meant to close.
Document the manual OTP-reset process as carefully as any other security control, including who is authorized to perform it and what proof of identity they must collect first. This single written procedure prevents more real-world account takeovers than almost any technical setting.
In Practice
Real-World & Industry Examples
OTP is not a theoretical exercise — it is one of the most deployed security controls in modern software, and the pattern shows up across very different kinds of organizations.
Enterprise internal tools
Large companies frequently run Keycloak as the identity layer in front of dozens of internal applications — HR systems, source-code repositories, cloud consoles, and finance dashboards. A single realm with OTP enforced as a Required step means employees log in once with 2FA and receive access across the entire internal ecosystem through single sign-on, while the organization gains a single, consistent place to enforce and audit the policy rather than configuring 2FA separately in every application.
Customer-facing SaaS platforms
Software-as-a-service companies often run a second, separate Keycloak realm specifically for customer accounts, distinct from their internal employee realm. OTP is frequently offered as an optional, user-enabled feature here rather than mandatory, letting security-conscious customers protect their own accounts without forcing extra friction onto every casual user, while premium or enterprise customer tiers may require it contractually.
Regulated industries: finance and healthcare
Organizations handling financial transactions or protected health information frequently operate under regulatory frameworks that explicitly require multi-factor authentication for access to sensitive systems. Keycloak’s combination of a mandatory OTP step, detailed event logging, and step-up authentication before sensitive actions gives these organizations both the technical control and the audit trail regulators expect to see.
Government and public-sector portals
Public-sector agencies running citizen-facing portals — for tax filing, benefits, or identity documents — commonly deploy Keycloak with OTP required for any account that can view or change personally identifiable information, reflecting the high sensitivity of the data even though the underlying budget and infrastructure constraints of the public sector make an open-source, self-hosted identity platform particularly attractive compared to commercial alternatives.
Questions Answered
FAQ
Wrapping Up
Summary & Key Takeaways
Two-Factor Authentication with OTP in Keycloak takes a widely trusted, open cryptographic standard — TOTP — and wraps it inside a configurable, no-code identity platform that any organization can deploy in minutes. The core idea never changes: a password proves you know something, and an OTP code proves you hold something, and requiring both together closes the door that stolen passwords alone would otherwise leave wide open. Everything else in this guide — the realm settings, the credential storage, the authentication flow engine, the event logs, the recovery procedures — exists to make that one simple idea reliable, auditable, and survivable at real-world scale.
Key Takeaways
- OTP is a second, independent proof of identity — a short-lived, six-digit code generated from a secret shared only between Keycloak’s server and the user’s authenticator app.
- TOTP is time-based, HOTP is counter-based — Keycloak supports both, with TOTP as the far more common default in modern deployments.
- The shared secret, created once at enrollment, is the foundation of everything — it never has to travel across the network again after the initial QR code scan.
- Authentication flows, not a single toggle, control enforcement — OTP can be Required, Alternative, or Conditional, letting organizations balance security against user friction.
- OTP is powerful but not invincible — it stops password-reuse and credential-stuffing attacks cold, but remains vulnerable to real-time phishing relays and does not replace good session security.
- Recovery planning is not optional — backup codes and a verified, documented reset procedure are what stand between OTP enforcement and a flood of legitimate users locked out of their own accounts.
- Monitoring turns OTP from a checkbox into a living control — Keycloak’s event logs let administrators spot brute-force attempts, suspicious credential resets, and phishing patterns as they happen, not months later.