Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Customization

Custom Authenticators and Keycloak SPIs

Extend Keycloak with Service Provider Interfaces: authentication flows and executions, writing a custom authenticator, factory registration, packaging, and flow requirement logic.

Keycloak is designed to be extended. Almost every behaviour you meet, from password checking to event storage to user storage, is a Service Provider Interface (SPI): a Java interface with a factory that Keycloak discovers at startup. If a setting does not exist for what you need, you can write a provider, drop it in as a JAR, and use it in the admin console like a built-in feature.

You cannot compile Java providers against Keycloak on this site, so the Java code below is read-only. It is a sketch of the shape of a provider, not a build you can run. The TryIt models how authentication flow requirements are evaluated, which you can run.

Common SPIs

SPI What it extends
Authenticator A step in a login flow (OTP, risk check, terms acceptance)
RequiredActionProvider Actions a user must complete (update password, accept terms)
EventListenerProvider React to events (send audit logs, call a webhook)
ProtocolMapper Add claims to tokens
UserStorageProvider Read users from a legacy database
PasswordHashProvider Support a legacy hash format
RealmResourceProvider Add REST endpoints under a realm
Policy provider Custom authorization policy type

Authentication flows first

Before writing code, understand the flow a custom step plugs into. Open Authentication in the admin console. A flow, such as browser, is a tree of executions (steps) and sub-flows. Each execution has a requirement:

  • Required: must succeed.
  • Alternative: at least one alternative in the same group must succeed. If any Required step exists at that level, alternatives at that level are ignored.
  • Conditional: a sub-flow that only runs when its condition steps (such as "user has role X") evaluate true.
  • Disabled: skipped.

You never edit built-in flows directly: duplicate one, edit the copy, then bind it under Action > Bind flow (browser flow, direct grant flow, and so on).

JS Stand-in: evaluating flow requirements

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Anatomy of a custom authenticator

An authenticator is two classes: the Authenticator that does the work and an AuthenticatorFactory that describes it. This is a trimmed sketch of a step that blocks logins outside allowed countries (illustrative: the lookup helper is left out):

Java
public class CountryAuthenticator implements Authenticator {

    @Override
    public void authenticate(AuthenticationFlowContext context) {
        String ip = context.getConnection().getRemoteAddr();
        String country = GeoLookup.countryOf(ip);          // your own helper
        if (!Set.of("DE", "FR", "NL").contains(country)) {
            context.failure(AuthenticationFlowError.ACCESS_DENIED);
            return;
        }
        context.success();
    }

    @Override public void action(AuthenticationFlowContext context) { }
    @Override public boolean requiresUser() { return false; }
    @Override public boolean configuredFor(KeycloakSession s, RealmModel r, UserModel u) { return true; }
    @Override public void setRequiredActions(KeycloakSession s, RealmModel r, UserModel u) { }
    @Override public void close() { }
}

The key methods:

  • authenticate runs when the step starts. It ends the step with success(), failure(error), attempted() (the step did not apply), or shows a form with challenge(response).
  • action handles the form the user submitted after a challenge.
  • requiresUser says whether a user must already be identified.
  • configuredFor and setRequiredActions decide if the user needs to set something up first (like registering an OTP device).

The factory returns an ID, a display name, the allowed requirement choices, whether it can be configured, and creates the authenticator instance:

Java
public class CountryAuthenticatorFactory implements AuthenticatorFactory {
    public static final String ID = "country-check";
    @Override public String getId() { return ID; }
    @Override public String getDisplayType() { return "Allowed countries"; }
    @Override public Authenticator create(KeycloakSession session) { return new CountryAuthenticator(); }
    // other required methods omitted for brevity
}

Registering and packaging

Keycloak finds providers using Java's ServiceLoader. Create a file in the JAR:

TEXT
META-INF/services/org.keycloak.authentication.AuthenticatorFactory

containing the factory's fully qualified class name, one per line. Build the JAR with Maven or Gradle, using Keycloak dependencies with the provided scope matching your server's version exactly. Copy the JAR into the server's providers/ directory, run kc.sh build (Quarkus distribution), and start. In a container, do the copy and build in your Dockerfile so the image is ready, then start with --optimized.

After restart the new step appears in Authentication, in a duplicated flow, under Add step. Add it, set a requirement, and bind the flow.

Testing and safety

  • Use the same version of the Keycloak libraries as the server; SPI interfaces change between majors.
  • Write unit tests for pure logic, and an integration test with Testcontainers against a real Keycloak container.
  • Never block the request thread with slow network calls; set tight timeouts.
  • Do not log passwords, OTP codes, or full tokens.
  • Keep providers small. Every provider is custom code in the most sensitive component of your system: review it like security code.

Alternatives to Java code

Before writing a provider, check for a built-in option:

  • Conditional flows plus built-in conditions (role, user attribute, level of authentication).
  • Protocol mappers for extra claims (see protocol mappers).
  • Client scopes and policies.
  • Event listeners shipped as separate small services that read events from the Admin API or a message queue.
JS Stand-in: should this be a provider?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which requirement means a step must succeed?

    Required steps must succeed for the flow to continue; alternatives are only used when no required step exists in the group.
  2. 2. How does Keycloak find a custom AuthenticatorFactory in your JAR?

    Keycloak uses the Java ServiceLoader mechanism.
  3. 3. Why should you duplicate a built-in flow before changing it?

    Built-in flows are read-only; copy, edit the copy, and bind it.
  4. 4. When should you prefer a protocol mapper to a custom provider?

    Mappers add claims without code; providers are for new behaviour.

Summary

  • SPIs let you extend Keycloak with Java providers loaded from providers/.
  • Authentication flows are trees of executions with Required, Alternative, Conditional, Disabled requirements.
  • An authenticator pairs an implementation with a factory registered through ServiceLoader.
  • Match library versions to the server and keep providers small and safe.
  • Prefer built-in options before writing code.

Next: Protocol Mappers and Custom Claims