Keycloak TOTP authenticator apps: when teams need them
A team that must add a second factor to Keycloak logins quickly, without buying hardware tokens, can start with time-based one-time passwords. Keycloak supports OTP policies for authenticator apps such as Google Authenticator and FreeOTP, so users enroll an app on their phone and enter a short rotating code at sign-in. The server administration guide documents these OTP policies in the realm settings, and they are the control point for every TOTP decision on the realm. Before enabling anything, confirm the apps your users will install and test enrollment with each one, since app behavior varies at the edges.
The OTP policy controls four settings: the algorithm, the number of digits, the period (how long each code is valid) and the look-ahead window (how many past or future codes the server accepts to tolerate clock drift). Most teams keep the defaults that the authenticator apps expect and change only what a written requirement forces. A shorter period or a wider look-ahead makes the factor easier to use on skewed devices but gives an attacker more time or more candidate codes, so record the reason for any change. Confirm the exact field names and accepted values in the current administration guide for your release, because they are part of the configuration you will export and review.
TOTP sits below passkeys and FIDO2 security keys on the strength scale. A TOTP code is a shared secret that the user can type into a phishing page, and it does not bind the login to the site being visited. Passkeys and security keys use WebAuthn, which is origin-bound and resists phishing, so they are the better fit where the requirement calls for phishing-resistant authentication, such as administrator access. Choose TOTP when the requirement is an additional factor for a broad population and phishing resistance is not mandated. If an auditor or security review asks for phishing-resistant MFA, TOTP alone will not satisfy it, and the design should move to WebAuthn for those users.
OTP policy settings and when each fits
This table compares each Keycloak OTP policy setting for authenticator apps against the trade-off between user app compatibility and strength. Read each row before changing a default, and confirm with your chosen apps which values they accept. The main takeaway is that the defaults are the safest starting point, and stronger values only help if every enrolled app supports them.
| Setting | What it controls | Compatibility versus strength | When to change it |
|---|---|---|---|
| OTP type (TOTP or HOTP) | TOTP codes change with time; HOTP codes change with each use of a counter | TOTP is widely supported by authenticator apps; HOTP needs counter sync and is less common in consumer apps | Use TOTP for most users; choose HOTP only if a specific device or legacy system requires it |
| Hash algorithm | The hash function used to generate codes (SHA-1, SHA-256 or SHA-512) | SHA-1 has the broadest app support; SHA-256 and SHA-512 are stronger but some apps ignore or reject them | Move off SHA-1 only after confirming each app you support handles the chosen algorithm |
| Number of digits | Length of the one-time code users type | Six digits is the common app default; eight digits adds guessing resistance but some apps display only six | Increase to eight only if every target app displays and accepts that length |
| Period | How many seconds each TOTP code remains valid | Thirty seconds is the widely used default; shorter periods shrink the replay window but raise clock-sync failures | Shorten only with tested clock sync across users' devices and your server |
| Look-ahead window | How many future time steps the server accepts to tolerate clock drift | A larger window tolerates more drift but widens the set of codes an attacker could try | Keep it small; widen only for documented drift problems and review the trade-off |
| Supported OTP application | Which authenticator apps users may enroll with, as your policy and documentation describe them | Apps differ in hash, digit and period support; FreeOTP and Google Authenticator behave differently for some settings | Confirm each app with a test enrollment before publishing the policy to users |
| Replay protection and reuse | Whether a code can be used more than once within its valid window | Stronger reuse controls add friction for users who submit a code twice; they reduce the window for interception | Review against your requirement; TOTP alone does not resist phishing, so use a stronger factor where that is required |
How to configure the OTP policy and enrollment in Keycloak
This sequence sets the realm OTP policy, places OTP into the login path, enforces enrollment for users, and confirms that authenticator apps produce logins and tokens that behave as intended.
Confirm the OTP policy requirements
Before changing anything, the security owner and the Keycloak administrator agree on the algorithm, digit count, period and look-ahead window the organization accepts, and which authenticator apps users will run. Record the values in the change ticket so the realm settings can be checked against them later. Keycloak's server administration guide documents the OTP policy options, so confirm each option against the version you run. The step is done when the agreed values are written down and approved.
Set the OTP policy in the realm
In the admin console, open the realm, go to Authentication, then the Policies area, and set the OTP policy for the realm. Choose the OTP type (time-based for authenticator apps), the hash algorithm, the number of digits, the period and the look-ahead window to match the requirements from the previous step. Save the policy and reopen it to confirm the stored values match what you entered. Use a test realm first where possible, because policy changes affect every user who enrolls afterward.
Add OTP to the browser login flow
Duplicate the browser flow, then add the OTP form step as Required, or place it inside a conditional sub-flow if only some users or clients need a second factor. Bind the copied flow to the browser flow for the realm and keep the original flow for rollback. Confirm the flow diagram shows the OTP step in the intended position and that no alternative path bypasses it. Conditional branches are covered in separate guidance, so check them against that design before you go live.
Set the OTP required action for enrollment
Enable the Configure OTP required action in the realm, and set it as a default action if every new user must enroll at first login. For existing users, assign the required action to the accounts that need to enroll, either individually or through a script run against the Administration REST API. Verify on a test account that the next login presents a QR code and a manual secret, and that the account cannot finish login without completing enrollment. Record which users were assigned the action so you can track completion.
Test enrollment with Google Authenticator and FreeOTP
Enroll a test user with Google Authenticator and again with FreeOTP, scanning the QR code on each device. Log out, sign in with the password, and enter the current six-digit code, or the number of digits you configured. Confirm that the app generates the same codes Keycloak expects and that the login completes. Also try a wrong code and an expired code to confirm that the rejection message is shown and the attempt is logged. Both tests should pass before you widen enrollment.
Check clock drift and look-ahead effects
Failed logins with correct codes usually come from device clock drift or from a look-ahead window that is too narrow for the devices involved. Ask a user with a drifted phone to sign in, then compare the device time with the server time, and widen the look-ahead only if the policy allows it. Keep the window as narrow as your requirement permits, because a wider window accepts older codes for longer. Record the outcome so the help desk knows which symptoms point to drift instead of a misconfigured policy.
Verify the login path and token behavior
Sign in through a test application, then inspect the resulting tokens and event log. Confirm that the authentication methods and any acr or amr values reflect the OTP step, and that the event log shows the OTP validation. Repeat the login through every client and flow that should require OTP, and through any path that should not, to confirm the behavior matches the design. The step is complete when the test results, flow screenshots and token samples are filed with the change record.
How the TOTP check fits into the Keycloak login flow
The sign-in starts in the user's browser, where the password is submitted to Keycloak's browser flow. Keycloak then evaluates the OTP sub-flow and asks for a one-time code. The authenticator app on the user's device computes that code from the shared secret and the current time, and Keycloak checks it against the OTP policy, including the look-ahead window. Only after that check does Keycloak issue the session and tokens. Check that the secret never leaves Keycloak's enrollment step in plain form and that the device boundary is understood by your auditors.
The TOTP check sits between the password step and token issuance, across the device boundary.
Security considerations for TOTP enrollment and storage
TOTP is only as strong as the secret behind it. The cards below cover the places that secret and its codes can leak: the enrollment screen, the login form, the network path, and the admin console that sets the policy. Each risk has one control you can check before go-live.
Secret exposure during QR enrollment
During enrollment, Keycloak shows a QR code and a text secret that encodes the shared key for the user's authenticator app. Anyone who sees that screen, or a screenshot of it, can generate valid codes for the account. Restrict where enrollment runs, avoid recording or screen-sharing the setup page, and make sure the enrollment step is completed only by the account owner. Confirm that the required action for OTP setup is reached only after a normal password login.
Keycloak docsPhishing of one-time codes
A TOTP code is valid for a short window and can be typed into a fake login page that relays it to the real one within that time. TOTP does not bind the code to the site the user is on, so it resists password theft but not real-time phishing. Treat TOTP as a second factor for ordinary users, and plan a phishing-resistant method such as WebAuthn for administrators and high-risk applications. Test the flow with a relay-style phishing simulation before relying on it.
Replay within the validity window
A code accepted once can be reused by an attacker who captured it, as long as Keycloak still accepts it. The OTP policy's look-ahead setting widens the set of codes accepted at any moment, which increases this window. Keep look-ahead at the smallest value your users' clock drift requires, and confirm that Keycloak rejects a code that has already been used. Ask your Keycloak team to show this behavior in a test realm.
TLS on all communication
The secret, the enrollment page, the password and the submitted code all cross the network during enrollment and login. Without TLS on every hop, including the link from the reverse proxy to Keycloak where it is used, those values can be intercepted. Keycloak's production guidance calls for TLS on all communication, so confirm certificates are valid, HTTP redirects to HTTPS, and internal hops are encrypted or isolated.
Production guideProtecting the admin console that sets OTP policy
Whoever can change the OTP policy or the authentication flow can weaken MFA for every user in the realm. Keep the admin console and Administration REST API on a separate hostname or context path from public frontend URLs, limit access to administrator networks, and require a strong second factor for administrators. Review who holds realm admin roles and log every change to the OTP policy and the browser flow.
When TOTP is not strong enough for the requirement
TOTP is a reasonable second factor for many workforce and customer logins, but it is not phishing-resistant. A six-digit code can be typed into a convincing fake login page or relayed by an attacker in real time, so the code remains valid for the attacker during its short window. If a requirement says the second factor must resist phishing and relay, TOTP alone does not meet it, and the design should move to WebAuthn passkeys or FIDO2 security keys. Those credentials are bound to the origin of the site, so a fake page cannot get a usable response.
Whether TOTP is enough is a decision about assurance, not about Keycloak. The requirement may come from an external auditor's control test, a regulator, a customer security questionnaire, or an internal policy that sets a minimum authentication level for administrators, privileged roles or sensitive applications. Start by writing down which accounts and applications the requirement covers, what threat it is meant to stop, and the evidence an assessor will ask for. Ask the assessor or your compliance lead to confirm the exact wording, because no single framework should be assumed to mandate a particular method. Keycloak's OTP policy can still enforce the algorithm, digits and period for TOTP users, but it cannot make a TOTP code phishing-resistant.
Once the requirement is clear, the next choices are design choices. For a population that can move to passkeys, the Keycloak server administration guide describes the passwordless and WebAuthn options that the sibling topics cover in detail. For a narrower group such as administrators or high-value roles, hardware security keys are often the practical starting point. For sensitive actions inside a broader application, step-up authentication can request a stronger login only when needed. Plan these alongside your recovery process, since a stronger factor that users lose is a help desk problem of its own.
Limits to confirm in your environment
TOTP works well as a baseline second factor, but its strength depends on choices your environment makes around it. The cards below cover what to confirm about users' apps, server clocks, lost-phone recovery, the Keycloak version you run, and how your proxy and hostnames shape enrollment.
Authenticator app compatibility
Not every authenticator app accepts every OTP setting. Before you fix the algorithm, digit count and period in the OTP policy, list the apps your users actually run, including the ones on managed corporate devices. Test enrollment and code acceptance in each app with a pilot group. Confirm that each app accepts the exact settings you chose, because a mismatch shows up as failed logins rather than a clear error.
Keycloak docsClock synchronization on servers and devices
TOTP codes depend on the time. The Keycloak server and each user's phone must agree on the current time window, and drift on either side causes rejected codes. Confirm that your servers run a time sync service with a trusted source, and that managed phones have automatic time enabled. Check how your look-ahead setting absorbs small drift, and treat a large or growing drift as an incident rather than tuning it away.
Recovery when phones are lost
A TOTP secret lives on one phone, so a lost, wiped or replaced device locks the user out. Decide before rollout how users recover: whether recovery codes are issued at enrollment, who in the help desk verifies identity before resetting OTP, and how a re-enrollment is required. Confirm that the admin reset path works for the realms you run, and that the reset itself is logged for audit.
Behavior of your Keycloak version
OTP policy options and their defaults can change between releases, and the upgrade notes for each version list behavior changes you need to read. Identify the exact Keycloak version you run, read the upgrade notes for every version between it and your target, and retest OTP enrollment and login after each upgrade. If you run a distribution such as the Red Hat build, confirm its support matrix separately from the upstream project.
Upgrading guideReverse proxy and hostname effects
Enrollment shows a QR code and a secret tied to the issuer name, so the hostname Keycloak advertises matters. Confirm the frontend URL, the hostname users reach through your reverse proxy, and any path rewriting, since a mismatch can produce enrollment codes that do not match the issuer your users expect. Keep the admin console on a separate hostname or path from public frontend URLs, as the production guide recommends.
Production guideStrength against your requirement
TOTP is a shared-secret factor that can be phished by a relay in real time, so it may not meet a requirement for phishing-resistant authentication. Map your framework's authentication controls to the factor you choose, and confirm with your assessor whether TOTP satisfies them for privileged or sensitive access. If it does not, plan for WebAuthn or passkeys for those users instead of extending TOTP.
Questions buyers ask about TOTP in Keycloak
Can we set up TOTP in Keycloak with our own team?
Yes, in most cases. Keycloak ships with OTP support in its authentication flows and an OTP policy in the realm settings, so a team with Keycloak administration skills can enable it, choose the algorithm, digits and period, and test enrollment with a few users. The harder part is the design around it: which flows require OTP, how users recover a lost device, how administrators are protected, and how the setting is tested so no login path skips it. Teams that already run Keycloak in production usually handle the basic setup in-house and ask for outside help only when the design spans several realms or applications. Confirm your team's Keycloak experience and your change control process before deciding.
What drives the effort of a TOTP rollout?
The effort follows the design, not the number of clicks in the admin console. The main drivers are:
- Number of realms and clients, since each realm carries its own flows, policies and required actions.
- Custom authentication flows, such as conditional OTP or per-client overrides, which need their own test cases.
- Recovery design, including recovery codes, admin resets and help desk checks for lost devices.
- User population size and the number of user groups that need different enrollment handling.
Each additional realm or custom flow adds configuration, testing and documentation. Ask any provider to list these drivers in the written scope so you can see which ones apply to you.
What does our team need to provide for a TOTP engagement?
A TOTP engagement depends on your identity owners making decisions and your testers having real devices. Expect to provide:
- Identity owners who can approve the OTP policy values and the recovery process.
- A set of test users covering each user group, role and application that will see the second factor.
- A list of authenticator apps your users actually use, such as Google Authenticator or FreeOTP, so the test matrix matches reality.
- Access to a non-production Keycloak instance and the change approval path for production.
- A named help desk contact who will handle lost-device requests during the pilot.
Without these inputs, the work tends to stall at the decision points rather than in the configuration itself.
How long does a TOTP implementation take?
The scope sets the duration. A single realm with one login flow, a standard OTP policy and a documented recovery path is a much smaller piece of work than several realms with conditional flows, step-up rules and a help desk process. Timelines should come from a written scope that lists the realms, flows, applications, user groups, test cases and approval steps. Ask any provider to tie each phase, including the pilot and the production change window, to a named deliverable. Be cautious of any timeline quoted before the scope is agreed.
Is Keycloak's OTP support free under the Apache 2.0 license?
Keycloak is licensed under Apache 2.0, and its OTP support, including the OTP policy and authenticator app enrollment, is part of the open source server. Using it does not require a license fee from the Keycloak project. Your costs are the infrastructure to run Keycloak, the staff or partner time to configure and operate it, and any commercial support you choose to buy. If you want vendor-backed support, the Red Hat build of Keycloak is a separate supported distribution with its own subscription terms, so confirm those terms directly with Red Hat before budgeting. Your legal team should also confirm how the Apache 2.0 terms apply to any custom extensions you write.
When is TOTP not strong enough for our requirements?
TOTP is a shared-secret, time-based code that a user types in, so it can be phished in real time and does not bind the login to the site being used. If your requirement calls for phishing-resistant authentication, such as for administrators or high-risk applications, TOTP alone is usually not enough and you should evaluate WebAuthn or passkeys. Check the requirement's wording with your compliance lead, and confirm what your assessor expects before choosing a factor. TOTP can still be a reasonable choice for lower-risk applications where a second factor is required and users cannot yet use hardware keys.
What are the common TOTP settings engineers get wrong?
The most common mistakes involve the OTP policy values and the look-ahead window. Engineers should confirm the algorithm, number of digits and period with the authenticator apps your users run, because some apps support fewer options than others. The look-ahead window controls how many future codes are accepted, so a wide window weakens the factor and a narrow one causes failed logins when device clocks drift. Also check that the policy applies to the realm and clients you expect, that required actions enroll users at the right moment, and that the admin console is protected by a stronger factor. Verify each setting by logging in with real apps on a test realm before changing production.
When is a partner worth bringing in for TOTP?
A partner is worth considering when the design has more moving parts than your team can review in its normal cycle. Typical triggers include several realms, conditional or step-up flows, a large or varied user population, an upcoming audit that needs evidence, or a lack of in-house Keycloak operators. DeployOpen plans, implements and tests self-hosted open source platforms inside your own infrastructure, and most engagements are fixed-scope with the scope, deliverables and timeline agreed in writing before work starts. It does not issue audit reports, so an independent auditor still reviews the evidence. Ask for a written scope and a quote before deciding.
How DeployOpen scopes a TOTP rollout
A written scope comes before any change to the Keycloak OTP policy. Before work starts, DeployOpen agrees with the client which OTP settings will be used (algorithm, digits, period and look-ahead window), which browser flows will call the OTP step, which user populations must enroll, and how enrolled users will recover a lost device. The scope also names the realms and clients in play, the admin roles that can reset OTP credentials, and the authenticator apps your users are expected to run. Those decisions are recorded in the scope document so that the policy settings in the admin console can be traced back to a stated requirement rather than to a default someone left in place.
Once the scope is agreed, DeployOpen tests every login path the design creates, including password-only paths, reset flows, token refresh, and any client that overrides the browser flow. The goal is to find paths where MFA is skipped or applied inconsistently, such as a legacy client, an alternate identity provider, or a fallback flow that accepts a weaker second factor. Each finding is logged with the path, the expected behavior and the observed behavior, then retested after the fix. Clients should confirm that their test accounts cover enrollment, failed codes, and re-enrollment after a credential reset.
DeployOpen also prepares the evidence that a compliance assessment will ask for, including the exported realm configuration, the flow definitions, test results for each login path, and records of enrollment and recovery procedures. DeployOpen does not issue audit reports, attestations or certifications. Independent auditors and certification bodies make those determinations, so clients should confirm early which control statements their assessor expects to see and whether the evidence format suits that assessor.
How DeployOpen delivers Keycloak MFA work
DeployOpen plans, configures and hardens TOTP authenticator app enrollment in Keycloak inside your own infrastructure. We start from the written requirement, set the OTP policy and required actions, test the sign-in paths, and document what your security and compliance teams need to review.
How we scope
- Written scope names the realms, clients and user groups that will use TOTP enrollment and sign-in.
- Scope records the OTP policy values, such as algorithm, digits, period and look-ahead, and who approved them.
- Scope states which requirements TOTP cannot meet, so stronger factors are priced and planned separately.
How we build
- We configure the OTP policy and browser flow in a non-production realm, then promote it through your change process.
- We test enrollment with the authenticator apps your users actually run, including recovery and re-enrollment paths.
- We check that no client or flow override bypasses the second factor, and record each test result.
How we hand over
- You receive the realm export, flow and policy settings, and a written record of every OTP parameter chosen.
- Runbooks cover user enrollment, lost-device handling and admin reset of OTP credentials.
- Evidence packs list the controls and test results your auditors or security reviewers will ask to see.
How we support
- Fixed-scope engagements close with agreed deliverables and a handover review against the written scope.
- Ongoing support, upgrades and continuous testing are available as a retainer for Keycloak after go-live.
- Retesting follows any Keycloak upgrade, since authentication flows and policy defaults can change between releases.

