Conditional MFA in Keycloak by role, group or application

Conditional MFA in Keycloak asks for a second factor only where risk justifies it, using conditional sub-flows and per-client flow overrides, with testing to confirm no path skips MFA by accident.

On this page

Conditional MFA in Keycloak by role or group: when teams need it

Require a second factor only for the roles, groups or applications where the risk justifies the extra step, and keep it on for everyone else only where policy says so. In a mixed user population, a single browser flow that prompts every user for OTP or WebAuthn on every login slows down people who touch low-risk tools, while a flow that exempts whole groups without a documented reason leaves gaps that an auditor or attacker will find. Keycloak's authentication flows are the place to make that decision explicit. The server administration guide documents conditional authenticators and conditional sub-flows that evaluate conditions such as user role, group membership and user attributes before a step runs, and per-client flow bindings that let one application use a different browser flow from the realm default. Confirm the exact condition types and their evaluation order in the version you run, since the conditions and their names are documented in the server administration guide and can change between releases.

The trade-off sits between blanket MFA and risk-based MFA. Blanket MFA is simpler to design, simpler to explain to an auditor and harder to misconfigure, because every path requires the same factors. Its cost is friction for users and help desk load on enrollment and recovery. Risk-based MFA asks for a second factor only when a signal such as role, group, client or sensitivity of the target application says it should. Keycloak can express the role and group conditions directly, but it does not decide risk for you. Before building conditions, list the applications and roles, mark which ones handle regulated data or administrative actions, and decide which exemptions, if any, need a named owner and review date. Ask your implementation partner or internal team to write those decisions down first, because the flow configuration should follow from them rather than define them.

Each conditional branch is a potential bypass, so the design must come with tests. Treat a user who holds a privileged role but reaches an application through a client with a different flow as a case to test explicitly, along with users in more than one group, users with no matching condition and any flow an application can fall back to. The check is not complete until you have confirmed, for each combination you intend to protect, that the second factor is requested and that an evaluated token reflects it. Record the test results and the flow configuration as evidence, and plan to rerun them after every change to flows, groups, roles or client bindings.

Which condition fits which access rule

Role conditions key on realm or client roles assigned to a user, either directly or through composite roles and group membership. They fit when the organization already models access as roles and when the set of people who need a stronger login is stable and clearly named, such as finance approvers or support staff with billing rights. Their main trade-off is that role composition can be deep. A user who inherits a role through a composite or a parent group may match the condition without anyone expecting it, so the effective set must be checked rather than assumed from the role name.

  • What it keys on: the presence of a realm or client role in the user's effective role mappings, including inherited mappings.
  • When it fits: a small, stable set of privileged roles that map cleanly to a business function.
  • Main risk: composite roles that pull a privileged role into users who were never meant to have it.
  • Maintenance cost: every new role that carries sensitive rights has to be added to the flow logic.
  • Check: list the effective roles for a sample of users in each population, not only the directly assigned ones.

Before relying on a role condition, confirm in a test realm exactly which users match it after composites are expanded.

How to build a conditional MFA flow in Keycloak

This sequence turns a blanket second-factor requirement into a flow that challenges only the users, groups or applications your risk model names, and proves with test logins that no path skips MFA by accident.

  1. Inventory clients, roles and groups needing MFA

    Your security owner and application owners list each client, realm role, group and client scope that should trigger a second factor, along with the condition that identifies them (a role, a group membership, a user attribute or a scope requested by the application). Record which applications already sign in through the realm and which users fall outside every condition. The output is a signed-off table that maps each population to its required factor, and it is the input for every later step. Confirm the mapping with the people who own the applications before you change anything in the realm.

  2. Copy the browser flow for change control

    In the admin console, an administrator duplicates the built-in browser flow under a new name, such as a conditional MFA browser flow, and leaves the original untouched as a rollback reference. The copy keeps the existing username and password step and the cookie check, so normal sign-in behavior does not change while you build. Confirm the copy appears in the flow list and that the realm still uses the original flow as its binding until you switch it in a later step.

  3. Add a conditional sub-flow with the chosen condition

    Inside the copied flow, the administrator adds a conditional sub-flow after the password step and sets its condition to match the inventory, for example a conditional role or group check, or a client-scope or user-attribute condition where your Keycloak version provides it. Confirm the exact condition types available in your release in the server administration guide before you rely on them. The sub-flow is complete when its condition is saved and its requirement is set to conditional, which makes it run only for matching sign-ins.

  4. Add the OTP or WebAuthn execution

    Within the conditional sub-flow, the administrator adds an OTP form or a WebAuthn authenticator execution and marks it required, so matching users must present the second factor. Choose WebAuthn where phishing resistance is the requirement, and OTP where authenticator apps are the approved method and the risk model accepts them. Confirm the factor policy settings in the OTP or WebAuthn policy pages. The step closes when a test user in a matching group is prompted for the factor and a test user outside it is not.

  5. Bind per-client overrides where needed

    Where one application needs a different flow from the realm default, the administrator sets the browser flow override on that client in its advanced settings and selects the conditional flow or a separate flow built for it. Keep overrides to the smallest set you can justify, because each one is another flow that must be tested and reviewed. The step is complete when the override is saved on each listed client and a sign-in to that client follows the flow you intended, which you check in the next step.

  6. Verify each path with test logins

    The QA owner builds a test matrix with one account per population: each role, each group, users with no matching condition, and users signing in through each client. Each account signs in to each relevant client, and the tester records whether the second factor was requested. Include a path that requests a non-matching scope or uses an alternate client, since accidental skips often sit there. The step closes when every row in the matrix matches the expected result, and failed rows go back to the flow for correction before the realm binding is switched.

  7. Switch the binding and export the configuration

    After the matrix passes, the administrator sets the conditional flow as the realm browser flow binding, records the change in your change log with the reviewer's name, and exports the realm configuration so the flow definition is stored in version control. Confirm the export contains the flow, its executions and the client overrides. Review the export at each Keycloak upgrade and after any role or group rename, because those changes can silently alter which users match the condition.

How a login path reaches or skips the second factor

The login starts at the Keycloak authentication flow, where the username and password step runs first. A Conditional sub-flow then evaluates the user's role, group, attribute or the client's flow override, and routes the user either to an OTP or WebAuthn challenge or straight to token issuance. Check the fallback branch carefully: users who match no condition should land on a deliberate default, and the acr and amr values written into the token should reflect which path was taken.

Conditional MFA routes each login to a second factor or a direct token issue.

Where MFA gets skipped by accident

Conditional MFA fails quietly when a login path never reaches the condition that asks for the second factor. The risks below sit at the boundary between Keycloak's flow model, client settings and token issuance, and each one has a specific check that exposes it before users do.

Alternative executions that short-circuit

In a Keycloak browser flow, an ALTERNATIVE execution succeeds as soon as any one alternative passes. If a password-only branch sits beside a conditional MFA branch, a user who satisfies the password branch can finish login without ever reaching the OTP or WebAuthn step. Review each flow top to bottom and confirm every path to a session includes a REQUIRED second-factor step under the conditions you intended. Walk the flow in the admin console and test each branch with a real user.

Keycloak docs

Client overrides that bypass the realm flow

Each client can be assigned its own authentication flow override, which replaces the realm browser flow for that application only. A new or edited client with an override pointing at a password-only flow will skip every conditional MFA rule defined at the realm level. Check the flow binding of every client, not just the realm default, and list any client that does not inherit the realm browser flow as a finding to justify or remove.

Direct grant and token endpoints

Flows used by the direct access grant (resource owner password credentials) or by other non-browser clients run through a separate flow binding and may not include the browser MFA steps at all. A client that accepts a username and password at the token endpoint can therefore issue tokens with no second factor. Disable direct access grants on clients that do not need them, and test the token endpoint with the same accounts you use for browser tests.

Role changes missing from active sessions

Conditional MFA that depends on a role or group decides at login. A user granted a sensitive role mid-session keeps an existing session that was authenticated under the older condition, so the new privilege is not backed by the stronger factor. Confirm how long existing sessions live, and test the flow by changing a role, starting a fresh login and checking which steps run. Pair this with step-up checks for sensitive actions.

User-editable attributes used as conditions

If a condition reads an attribute that users can change in the account console, such as a department, location or a custom flag, a user can edit the value to match a branch that skips MFA. Identify which attributes drive conditions, restrict who can write them in the account console and user profile settings, and make administrator-managed attributes the only source for high-risk decisions.

New clients inheriting permissive defaults

A client created without deliberate review can inherit default bindings, default client scopes or a flow that was never intended for it. Treat client creation as a security change: require a checklist that confirms the flow binding, the required scopes that feed the conditions and whether direct grants are enabled. Re-run your MFA test set whenever a client is added, and export client configuration so changes are visible in review.

Production guide

Testing that no login path skips MFA

Test every combination of client, condition outcome, grant type and broker path, not just the happy login. A conditional MFA design fails quietly when one route bypasses the sub-flow, so build a test matrix with one row per enabled client, one row per branch of each conditional (role or group matched, not matched, attribute missing, client scope absent), one column per grant type that client enables (authorization code, refresh token, client credentials, device flow where used, and token exchange if configured), and one row per identity provider broker path. Each cell records whether a second factor was required, which authentication methods appear in the amr claim, and what acr value was issued. Where a client has a per-client flow override, test that override separately from the realm browser flow, because the override is what that client actually runs.

Run each test in a fresh browser session with no existing Keycloak SSO cookie, and clear any cached token or remembered-device state before the next case. A session that already completed MFA will hide a regression, and so will a user who has an earlier login from a broker. Verify the tokens themselves, not only the login screen: check that the claims downstream applications rely on, such as acr, amr, roles and groups, match what the matrix expects, and check that refresh tokens do not extend a session past an MFA decision the policy requires. Confirm with your own environment and with each application team which claims they actually validate, because a claim nobody checks is not a control.

Rerun the full matrix after every change to a flow, a conditional, a client, a role mapping or a broker configuration. Treat the matrix as release evidence and store the results with the configuration export that produced them. Ask any partner or internal team to show the matrix, the failing cases fixed and the retest results before sign-off. The same matrix also supports the evidence work that auditors ask for on authentication requirements, so keep it under version control alongside the realm configuration.

Security and operational considerations

Conditional MFA moves security decisions into flow configuration, logs and token settings, and each of those can drift after launch. The cards below cover the controls that keep a conditional design doing what it was meant to do, and the operational load that comes with requiring a second factor for users who never had one.

Restrict who can edit authentication flows

Conditional sub-flows, per-client overrides and step-up conditions all live in the authentication configuration of the realm. Anyone who can edit a flow can remove a condition or switch a required step to alternative, which quietly removes MFA for a population. Limit flow editing to a small named group of administrators, and confirm in your version which admin roles can reach the Authentication section of the admin console and the Administration REST API. Put those endpoints behind the hostname or path restrictions described in the production guide.

Production guide

Review flow exports as code changes

A flow change that looks cosmetic in the console can alter which users reach a second factor. Export the realm configuration before and after each change, diff the authentication flows and executions, and require a second person to approve the diff before it reaches production. Keep the exports in version control so you can show auditors which configuration was live on a given date. Confirm the export formats and tooling your release supports before building the process around them.

Log authentication events for audit

Auditors will ask which users passed a second factor, which were exempted by a condition, and when a flow changed. Decide what you need to answer those questions and check which authentication events the server writes to its logs, and at what level, in your Keycloak version. Persisting login failures to the database is a default in the 26.8 line according to the upgrade notes, but other event details may need explicit configuration. Forward logs to a central store and test that a sample login from each condition branch appears with the fields you need.

Upgrade notes

Align session and token lifetimes with step-up

A user who completed MFA hours earlier can keep a session that satisfies a conditional check, so a sensitive action may not trigger a new factor. Compare the SSO session idle and maximum lifetimes with the window your risk model allows, and check which access token lifetimes apply to each client. Confirm how the authentication level and authentication methods claims are populated in tokens your applications receive, because a client that reads only the login time may not see a stronger factor was used. Test with a session that is already active, not only with a fresh login.

Plan help desk load before enforcing MFA

Newly required MFA generates enrollment requests, lost device tickets and users who cannot complete the second factor on a shared or unmanaged device. The cost falls on your help desk and identity team, and it recurs with every device replacement and staff change. Estimate volume by counting affected users per group, decide which recovery paths you will allow, and set up identity verification steps before the rollout starts. Phased enforcement by group lets support absorb the load in smaller batches. Ask any implementation partner to price this work as a separate line item, since it is operational effort rather than configuration.

Monitor conditions after each change

A condition that works at launch can stop matching when a role is renamed, a group moves or a client is re-registered. Build checks that run after each change: test accounts for every branch, a count of logins per authentication method, and an alert when the share of password-only logins for a protected application rises. Enable the metrics endpoint if your team wants these signals in Prometheus, and confirm the metric names in your release before writing alert rules.

Metrics guide

Questions teams ask before conditional MFA work

What drives the cost of conditional MFA work in Keycloak?

The main driver is how many distinct access paths you need to govern, not the number of users. Each combination of role, group, attribute, client scope and application that needs a different second-factor rule adds a branch to design, configure, and test. Cost also rises when the current flows have been customized, when MFA must work across several realms, or when the policy is not written down before build starts. Ask any partner for a quote built from a written list of clients, flows and conditions, with each branch listed separately. Recurring cost comes from reviewing the policy as roles and applications change, which is usually smaller than the initial build but should be budgeted as ongoing work.

How long does a build and test cycle usually take?

Duration depends mostly on the number of clients and authentication flows in scope and on how many conditions each flow evaluates. A single realm with one browser flow and a few conditional sub-flows is a small job. Each additional client that overrides the default flow, each new condition, and each approval step from security review adds test cases. Testing is the part teams underestimate, because every condition needs positive and negative paths, including sessions that started before a policy change. Ask for a timeline tied to a written test matrix, and confirm which environments and test accounts the client will provide.

What does the work need from our identity and security teams?

It needs decisions and access more than hours. The identity team should confirm the source of truth for roles, groups and attributes, and whether those values are reliable enough to drive a login decision. The security team should approve the MFA rule set, the list of applications in scope, and the acceptable second factors for each risk tier. Both teams should provide a non-production Keycloak realm that mirrors production, test accounts for each role, and a change window for rollout. Without these inputs, the build stalls on policy questions rather than configuration.

Can an internal team implement conditional MFA alone?

An experienced Keycloak administrator with access to a test realm can build simple conditional flows, and many teams do this in-house. The harder part is proving that no path skips MFA by accident, especially when several clients override the default browser flow or when a flow is updated after a Keycloak upgrade. Internal teams should ask whether they have capacity for independent testing, a documented rollback, and someone who can review the configuration against the written policy. A fixed-scope engagement can cover the build, testing and handover together, with the scope and deliverables agreed in writing first.

How do Keycloak upgrades affect custom MFA flows?

Custom flows are the part of a Keycloak deployment most likely to need attention after an upgrade, because they depend on authenticator behavior and flow structure that the project can change between releases. The Keycloak project plans four minor releases a year and says breaking changes in a minor release will be opt-in, but you still need to re-test each flow after upgrading. Check the upgrade notes for the target version, export the flows before the change, and rerun the full test matrix in staging. Confirm whether your upgrade plan includes this regression testing, since it is often omitted from the estimate.

What is the most common way conditional MFA fails?

The most common failure is a path that bypasses the second factor, such as a client that uses a different flow binding, a fallback flow left enabled, or a condition that evaluates to true for a user who should be challenged. Less visible failures include attributes that users can edit, groups that are assigned automatically, and token claims that a downstream application trusts without checking the authentication level. To reduce this risk, list every client and its flow binding, test each role against each client, and review the admin events that record flow changes. Ask any partner how they will show coverage across that list.

Does conditional MFA help with compliance evidence?

Conditional MFA can support access control and authentication requirements, but it does not by itself satisfy an audit. Auditors look for a documented policy, configuration that matches it, test evidence, and records showing the controls operated over time. DeployOpen prepares systems, controls and evidence for compliance assessments, but it does not issue audit reports, attestations or certifications; independent auditors and certification bodies do. Ask your auditor which control objectives they test before the build, so the test matrix and change records produce the evidence they need.

How DeployOpen scopes and delivers conditional MFA

DeployOpen approaches conditional MFA in Keycloak as a written, fixed-scope engagement inside your own infrastructure. We map which roles, groups and applications need a second factor, build the conditional flows, and test that no sign-in path skips MFA by accident before handing the configuration to your team.

How we scope

  • Inventory every realm, client and login path that currently reaches Keycloak, including APIs and admin access.
  • Agree in writing which roles, groups, attributes or client scopes trigger a second factor, and which do not.
  • Record the accepted factor types, enrollment rules and fallback policy so scope, deliverables and timelines are fixed before build.

How we build

  • Design conditional sub-flows and per-client flow overrides in a non-production realm that mirrors your production settings.
  • Configure the OTP and WebAuthn policies that the chosen second factors depend on, with required actions for enrollment.
  • Write a test matrix covering each user population, client and browser path, and run it until every path behaves as the design states.

How we hand over

  • Deliver the flow definitions, client mappings and test results as documentation your administrators can review and version.
  • Document the logic that decides when MFA is required, so auditors and security reviewers can trace each condition to a decision.
  • Walk your identity and operations staff through change procedures for adding roles, groups or applications later.

How we support

  • Offer ongoing support, Keycloak upgrade work and continuous testing as a retainer after handover.
  • Retest the conditional flows after each Keycloak minor release, since flow behavior changes can surface in upgrades.
  • Confirm with your team which support hours, escalation paths and change windows apply before the retainer starts.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.