What Is a Custom Authenticator in Keycloak?

What Is a Custom Authenticator in Keycloak?

A complete, beginner-friendly walkthrough of how Keycloak's login process can be extended with your own authentication steps — beyond passwords, OTPs, and the built-in defaults.

Think about airport security. Every traveler passes through the same general checkpoint, but airports don’t stop at just checking a boarding pass — they can add extra, specific checks: a random secondary screening, a biometric face match, a customs declaration review. Each of those is a distinct step slotted into the same overall security flow, and airports can add, remove, or reorder them without rebuilding the checkpoint from scratch. Keycloak’s custom authenticator feature works on exactly that principle for logins: it lets developers plug their own, purpose-built verification step into Keycloak’s authentication flow, right alongside the built-in ones like password checks and OTP.

1What Is a Custom Authenticator, Really?

Before touching any code, let’s fix the plain-English idea in place.

In Keycloak, the login process is built from a sequence of individual steps called an authentication flow. Each step in that sequence — checking a username, verifying a password, prompting for an OTP — is handled by a small, self-contained unit of logic called an authenticator. Keycloak ships with a solid set of these built in. A custom authenticator is simply a developer-written authenticator that plugs into that same mechanism, letting an organization add a verification step Keycloak doesn’t provide out of the box — checking a risk score, calling an external fraud-detection service, requiring a hardware token, or enforcing a company-specific business rule before letting someone log in.

Crucially, a custom authenticator isn’t a separate, parallel login system running alongside Keycloak. It becomes a first-class citizen of Keycloak’s own authentication flow — administrators can drag it into a flow through the admin console, mark it required or optional, and reorder it relative to any other step, exactly as if it had shipped with Keycloak itself.

Simple Analogy

Think of Keycloak’s login process as an assembly line, where each station performs one specific check before passing the item along. A custom authenticator is like a new inspection station a factory adds to its own assembly line — built in-house, but bolted into the same conveyor belt, running in whatever order the factory decides.

i
Where the name comes from

“Authenticator” is Keycloak’s own term for one pluggable step in a login flow — it doesn’t necessarily mean the step confirms identity by itself; a custom authenticator can just as easily enforce a business rule or gather extra context.

2Authentication Flows: A Quick Refresher

Understanding where a custom authenticator lives requires a quick look at the flow structure around it.

A Keycloak authentication flow is an ordered list of executions — each execution referencing one authenticator, plus a requirement describing how that step affects the overall outcome. An execution can be marked Required (must succeed for login to proceed), Alternative (any one of several alternatives succeeding is enough), Conditional (only runs if some condition is met), or Disabled (skipped entirely).

Must Pass

Required

The user cannot complete login without successfully passing this step.

One of Several

Alternative

Any one alternative in the same group succeeding is enough — for example, offering both OTP and a security key as valid second factors.

Situational

Conditional

Only evaluated when a defined condition holds true, such as the user belonging to a specific group.

Skipped

Disabled

Present in the flow definition but not actually executed during login.

A custom authenticator slots into this same structure as just another execution — it doesn’t need its own special flow type or separate configuration mechanism.

3Built-In vs. Custom Authenticators

It helps to see what Keycloak already offers before reaching for a custom one.

AspectBuilt-In AuthenticatorCustom Authenticator
SourceShips with KeycloakWritten by a developer, deployed as an extension
ExamplesPassword, OTP, WebAuthn, Identity Provider RedirectRisk scoring, external fraud check, custom device checks, business-rule gates
ConfigurationPre-defined settingsDeveloper-defined settings, exposed through the same admin UI pattern
Placement in FlowSame drag-and-reorder mechanismSame drag-and-reorder mechanism
!
Common Misconception

Reaching for a custom authenticator is not always necessary — many “extra step” requirements can already be met by combining and reordering Keycloak’s existing built-in authenticators inside a flow.

4Architecture: The Authenticator SPI

Custom authenticators are built against a well-defined extension point, not an unofficial hack.

Keycloak exposes this extensibility through its Service Provider Interface (SPI) system — a general pattern Keycloak uses throughout the codebase to let developers plug in custom implementations of specific behaviors. For authentication steps specifically, this is the Authenticator SPI, made up of a small number of cooperating pieces.

The Logic

Authenticator

Contains the actual verification logic — what happens when this step runs during a login attempt.

The Factory

AuthenticatorFactory

Describes the authenticator to Keycloak — its display name, configurable properties, and how instances of it are created.

The Packaging

Provider JAR

The compiled extension, registered with Keycloak through the standard Java service-loader mechanism, so Keycloak discovers it at startup.

flowchart LR
    F["AuthenticatorFactory
describes the step"] --> R["Registered with Keycloak
via SPI"] R --> A["Appears as an available
execution in Flow Editor"] A --> P["Admin adds it to a flow
and sets its requirement"] P --> L["Runs during real user logins"]
FIG 1 — Once registered, a custom authenticator becomes indistinguishable, from the admin’s point of view, from a built-in one.

5What an Authenticator Actually Does

Conceptually, every authenticator — built-in or custom — answers the same small set of questions during a login attempt.

1

Is this step applicable right now?

The authenticator can decide whether it even needs to run for this particular user or context.

2

What should the user see or do?

If user interaction is needed, the authenticator can present a form, a prompt, or a redirect as part of the login page.

3

Did this step succeed, fail, or need more input?

Based on the check performed, the authenticator tells Keycloak whether to proceed, block the login, or ask for something further.

4

Should anything be required afterward?

An authenticator can also trigger a required action, such as prompting the user to set something up before continuing.

These questions map to specific responsibilities defined by the Authenticator SPI, letting Keycloak treat wildly different custom logic — a risk check, a form prompt, a silent background verification — through one consistent, predictable contract.

6How a Custom Authenticator Plugs Into a Flow

Once built and deployed, using a custom authenticator is entirely an admin console configuration task.

It appears in the flow editor automatically

After a properly registered custom authenticator is deployed, it shows up in the list of available executions an administrator can add to any authentication flow, right alongside every built-in option.

Its requirement and position are fully configurable

An administrator decides whether the custom step is required, alternative, or conditional, and exactly where it sits relative to other steps — all without touching any code.

i
Practical Tip

Because the same custom authenticator implementation can be reused across many different flows and realms, it’s common to build one general-purpose custom step (like “check risk score”) and apply it selectively to just the flows or clients that need it.

7Building One: The Development Journey

At a high level, here’s what building and shipping a custom authenticator typically looks like.

1

Define the verification logic

Decide exactly what the step needs to check — a risk score, an external system’s response, a business rule — and design its success and failure outcomes.

2

Implement it against the Authenticator SPI

Write the logic and its accompanying factory, following the contract Keycloak expects for describing and instantiating the step.

3

Package it as a provider extension

Build the implementation into a JAR that registers itself with Keycloak’s service-loading mechanism.

4

Deploy it into the Keycloak server

Place the extension where Keycloak looks for providers, and restart or reload as required so it’s picked up.

5

Wire it into a flow through the admin console

Add the newly available execution to the relevant authentication flow, set its requirement, and test it thoroughly.

Here’s what actually happens when a user hits a flow containing a custom step.

sequenceDiagram
    participant U as User
    participant K as Keycloak
    participant CA as Custom Authenticator
    participant Ext as External System (optional)

    U->>K: Submits username/password
    K->>K: Required step — Password Authenticator passes
    K->>CA: Invoke custom authenticator
    CA->>Ext: Check risk / call external service (if needed)
    Ext-->>CA: Result
    alt Success
        CA-->>K: Step passed
        K-->>U: Continue to next step / issue tokens
    else Failure
        CA-->>K: Step failed
        K-->>U: Login denied or challenged further
    end
        
FIG 2 — A custom authenticator is simply invoked in sequence alongside built-in ones, and its outcome is treated exactly the same way by the flow engine.

9Common Types of Custom Authenticators

In practice, most custom authenticators fall into a handful of recognizable categories.

Risk-Based

Adaptive Risk Checks

Evaluates signals like unusual location or device to decide whether to require extra verification for this particular login attempt.

External Verification

Third-Party Fraud/Identity Checks

Calls an external service to confirm additional context about the user or device before allowing login to proceed.

Business Rule

Organizational Policy Gates

Enforces company-specific rules, such as blocking login outside approved hours or requiring an active subscription status.

Alternative Factor

Custom Second-Factor Methods

Supports a proprietary or industry-specific second-factor mechanism not covered by Keycloak’s built-in options.

10Making It Configurable

A well-built custom authenticator doesn’t hard-code every detail — it exposes sensible settings to administrators.

By implementing the configurable variant of the authenticator factory contract, a custom authenticator can define its own set of configuration fields — a threshold value, an external service URL, a toggle for strict versus lenient mode — which then appear directly in the admin console when that step is added to a flow, just like the configuration options for any built-in authenticator.

Why this matters

Exposing configuration this way means the same custom authenticator can be reused across multiple realms or clients with different settings, without needing separate code for each variation.

11Security Considerations

A custom authenticator becomes part of the login path itself, so it deserves the same rigor as any other security-critical code.

Fail Behavior

Fail closed on errors

If a custom check can’t complete — say, an external service is unreachable — it should generally deny or challenge the login rather than silently letting it through.

Input Handling

Treat all input as untrusted

Any data collected from the user or an external system during the custom step should be validated carefully, just as in any other security-sensitive code.

Testing

Test every outcome path

Success, failure, and error conditions should all be deliberately tested, since a subtle bug here directly affects who can and can’t log in.

Isolation

Keep external calls resilient

Custom authenticators calling out to external systems should handle timeouts and failures gracefully, so a slow third party doesn’t degrade login for everyone.

ANTI-PATTERN-01 Avoid
Problem

A custom authenticator silently treats any error or timeout from an external dependency as a pass, to avoid blocking users during outages.

Why It’s Harmful

This quietly turns a security check into a check that can be bypassed simply by making the dependency unavailable, which an attacker could exploit deliberately.

Correct Approach

Default to denying or challenging further on error, and address availability concerns through proper resilience patterns rather than a silent security bypass.

12Advantages, Disadvantages & Trade-offs

Custom authenticators unlock real flexibility, but that flexibility comes with real responsibility.

Advantages

  • Extends Keycloak’s login flow without forking or replacing the core product
  • Reuses the same flow editor, requirement model, and admin UI as built-in steps
  • Can encapsulate organization-specific rules or third-party integrations cleanly
  • Configurable per deployment, letting one implementation serve many use cases

Disadvantages / Trade-offs

  • Adds custom code directly to a security-critical path, raising the bar for careful testing
  • Requires ongoing maintenance as Keycloak’s SPI evolves across versions
  • Poorly written custom logic can degrade login reliability or performance for every user
  • Debugging login issues now spans both Keycloak’s own logs and custom code

13Design Patterns & Anti-Patterns

A few recurring habits separate maintainable custom authenticators from fragile ones.

Pattern: One Authenticator, One Responsibility

Keep each custom authenticator focused on a single check, composing several small steps in a flow rather than building one authenticator that tries to do everything.

Pattern: Expose Configuration Instead of Hard-Coding

Favor configurable fields over embedding environment-specific values directly in code, so the same authenticator can serve multiple realms or environments.

ANTI-PATTERN-02 Avoid
Problem

Building one large, monolithic custom authenticator that combines several unrelated checks — risk scoring, business rules, and a second factor — into a single implementation.

Why It’s Harmful

This makes the authenticator hard to test, hard to reuse selectively, and forces every consuming flow to accept the whole bundle even if only one part is actually needed.

Correct Approach

Split distinct checks into separate, focused authenticators, and compose them together within a flow using the requirement settings Keycloak already provides.

14Best Practices & Common Mistakes

A short, practical checklist for teams building their first custom authenticator.

1

Prototype the flow logic before writing code

Sketch out exactly where the new step belongs, what requirement type it should have, and how it interacts with existing steps first.

2

Test in a non-production realm first

Verify the new step behaves correctly across success, failure, and edge cases before applying it to a realm real users depend on.

3

Log meaningfully, without leaking sensitive data

Ensure the custom authenticator’s logs help diagnose issues without recording sensitive details like full risk-scoring payloads unnecessarily.

4

Track it through Keycloak version upgrades

Revisit custom authenticator code when upgrading Keycloak, since SPI details can evolve between major versions.

!
Common Mistake

Deploying a new custom authenticator directly into a production flow without first testing it as an alternative or conditional step, risking a full login outage if the new logic has a bug.

15Real-World Use Cases

Custom authenticators show up wherever an organization’s login requirements go beyond what ships by default.

Banking & Finance

Adaptive Authentication

Financial applications often add risk-based custom steps that trigger extra verification only for unusual login patterns, rather than for every user every time.

Regulated Industries

Compliance Gates

A custom authenticator can enforce industry-specific requirements, like requiring an up-to-date compliance training record before granting access.

B2B Platforms

Tenant-Specific Rules

A multi-tenant SaaS platform can use a custom authenticator to enforce rules that vary by customer, such as one tenant requiring a hardware key while another doesn’t.

Legacy Integration

Bridging an Existing System

Organizations migrating from an older identity system sometimes use a custom authenticator to check legacy credentials or flags during a transition period.

16Monitoring, Logging & Metrics

Because a custom authenticator sits directly on the login path, watching how it performs matters.

Track pass/fail rates for the custom step

A sudden shift in how often the step passes or fails can indicate either a genuine security event or a bug in the custom logic.

Monitor latency added to login

If the custom authenticator calls an external system, tracking the extra time it adds to each login helps catch performance regressions early.

Alert on repeated errors from the step

Frequent internal errors in a custom authenticator deserve prompt attention, since they can silently affect every user passing through that flow.

17Frequently Asked Questions

Q1Do custom authenticators require modifying Keycloak’s own source code?

No. They’re built as separate extensions using Keycloak’s SPI mechanism and deployed alongside the server, without needing to fork or modify Keycloak itself.

Q2Can a custom authenticator show its own login screen?

Yes. An authenticator can present a custom form or prompt to the user as part of the login process, in addition to performing purely background checks.

Q3Can the same custom authenticator be used in multiple flows?

Yes. Once deployed and registered, a custom authenticator is available to add into any authentication flow across the realm, and can be configured differently in each.

Q4Does a custom authenticator work for both login and registration flows?

It can, depending on how it’s built. Keycloak supports several types of flows beyond login, including registration and reset-credentials, and a suitably designed authenticator can be added to more than one.

Q5Is a custom authenticator the same thing as a custom protocol mapper?

No. A protocol mapper shapes what data ends up inside a token; an authenticator is a step in the login process itself, deciding whether and how a user proceeds toward getting that token in the first place.

Q6What happens if a custom authenticator throws an unexpected error?

Behavior depends on how the authenticator is implemented, but a well-built one should treat unexpected errors as a failure or challenge condition rather than allowing the login to proceed unchecked.

18Summary and Key Takeaways

A custom authenticator is Keycloak’s mechanism for adding a developer-defined verification step directly into the standard login process, built against the Authenticator SPI and configured through the same admin console tools used for built-in steps like password and OTP checks. It lets organizations enforce risk-based checks, business rules, or third-party verifications precisely where they’re needed, without forking Keycloak or building a separate authentication system alongside it. Because it sits directly on the login path, though, it deserves the same careful design, testing, and monitoring as any other security-critical code — particularly around how it behaves when something goes wrong.

Key Takeaways

  • It’s a pluggable step in a flow — built against Keycloak’s Authenticator SPI, not a separate login system.
  • It behaves like a built-in step — configurable and reorderable through the same admin console flow editor.
  • It answers a consistent set of questions — whether it applies, what the user sees, and whether the step passed or failed.
  • Configuration keeps it reusable — exposing settings lets one implementation serve many realms or clients.
  • Fail-closed design is essential — errors or unavailable dependencies should challenge or deny, not silently pass.
  • It’s best kept single-purpose — one focused check per authenticator, composed together in a flow.
  • It shines for organization-specific needs — risk-based checks, compliance gates, and business rules that go beyond Keycloak’s defaults.