Build a Keycloak webhook extension with the Event Listener SPI

In short
  • An event listener is a small jar that Keycloak calls on every user event (login, failed login, sign-up) and admin event (users, clients and roles created or changed).
  • Ours sends each event as JSON to a URL you choose, signed with HMAC-SHA256 so the receiver can prove it came from your Keycloak.
  • It only sends after Keycloak's transaction commits, and it sends asynchronously, so a slow receiver never slows down a login.
  • Three files, an 8 KB jar, tested on Keycloak 26.4.

Why use a webhook?

Without one, other systems have to poll Keycloak's Admin API to notice changes. A webhook pushes each event the moment it happens. Common uses:

  • Syncing new users to a CRM or billing system
  • Feeding an audit trail or analytics pipeline
  • Alerting your SIEM or Slack to bursts of failed logins (password spraying)

What you need

  • Java 17 or newer and Maven
  • Docker, to run Keycloak 26.4 and a test receiver

The three pieces of every Keycloak extension

PieceWhat it does
FactoryCreated once at startup. Reads config and creates providers.
ProviderCreated per request. Does the actual work.
Services fileOne line in META-INF/services so Keycloak can find the factory.

Step 1: A plain Maven project

Compile against Keycloak's SPI jars with provided scope, because Keycloak supplies them at runtime. Nothing gets bundled, so the jar stays tiny. Match keycloak.version to your server.

<properties>
  <maven.compiler.release>17</maven.compiler.release>
  <keycloak.version>26.4.0</keycloak.version>
</properties>
<!-- keycloak-core, keycloak-common, keycloak-server-spi,
     keycloak-server-spi-private, jboss-logging: all <scope>provided</scope> -->

List each jar explicitly. Maven doesn't pull in the dependencies of a provided jar, so leaving one out gives "package org.keycloak does not exist" errors.

Step 2: The factory

Keycloak creates the factory once, at startup. Its ID is the name you switch on in the admin console, and init() receives config from environment variables: KC_SPI_EVENTS_LISTENER_WEBHOOK_URL becomes config.get("url").

public class WebhookEventListenerProviderFactory implements EventListenerProviderFactory {
    public static final String ID = "webhook";

    @Override
    public void init(Config.Scope config) {
        url = config.get("url");
        secret = config.get("secret");
        http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
    }

    @Override
    public EventListenerProvider create(KeycloakSession session) {
        return new WebhookEventListenerProvider(session, http, url, secret);
    }
}

create() runs on every request, so keep it cheap. The HTTP client is built once and shared.

Step 3: The provider

Two callbacks: onEvent(Event) for user events and onEvent(AdminEvent, boolean) for admin events. Both build a small JSON body and pass it to send(). Three details make it safe for production:

private void send(Map<String, Object> body) {
    // only fire once Keycloak's transaction has committed
    session.getTransactionManager().enlistAfterCompletion(new AbstractKeycloakTransaction() {
        @Override protected void commitImpl() { post(toJson(body)); }
        @Override protected void rollbackImpl() { }
    });
}

private void post(String json) {
    HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Content-Type", "application/json")
            .header("X-Keycloak-Signature", "sha256=" + sign(json))   // HMAC-SHA256
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();
    http.sendAsync(request, HttpResponse.BodyHandlers.discarding());  // never blocks a login
}
  • After commit: you never announce a change that was rolled back.
  • Asynchronous: if the receiver is slow or down, users don't notice. Failures are logged.
  • Signed: the receiver recomputes the HMAC with the shared secret and rejects anything that doesn't match.

A user created through the console or the REST API (for example by an HR sync) arrives as ADMIN_CREATE, not REGISTER. REGISTER only fires for self sign-up.

Step 4: Register it and build

Create src/main/resources/META-INF/services/org.keycloak.events.EventListenerProviderFactory containing one line, the factory's full class name. Then build:

mvn -q package && ls -lh target/*.jar
# target/keycloak-webhook-listener-1.0.0.jar  (8.2K)

Step 5: Deploy to Keycloak 26.4

Start a small test receiver, then Keycloak with the jar mounted in /opt/keycloak/providers and the URL and secret passed as environment variables:

docker network create kc-demo
docker run -d --name webhook-receiver --network kc-demo -v ./receiver.mjs:/app/receiver.mjs \
  -e WEBHOOK_SECRET=demo-secret-123 node:22-alpine node /app/receiver.mjs
docker run -d --name keycloak --network kc-demo -p 8180:8080 \
  -v ./target/keycloak-webhook-listener-1.0.0.jar:/opt/keycloak/providers/keycloak-webhook-listener-1.0.0.jar \
  -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
  -e KC_SPI_EVENTS_LISTENER_WEBHOOK_URL=http://webhook-receiver:4000/keycloak \
  -e KC_SPI_EVENTS_LISTENER_WEBHOOK_SECRET=demo-secret-123 \
  quay.io/keycloak/keycloak:26.4.0 start-dev

The log shows a KC-SERVICES0047 warning that the provider implements an internal SPI. That's expected for event listeners: pin your Keycloak version and retest when you upgrade. Confirm Keycloak loaded it:

kcadm() { docker exec keycloak /opt/keycloak/bin/kcadm.sh "$@"; }
kcadm config credentials --server http://localhost:8080 --realm master --user admin --password admin
kcadm get serverinfo | jq '.providers.eventsListener.providers | keys'
# [ "email", "jboss-logging", "webhook" ]

Step 6: Switch it on and fire real events

Enable the listener on a realm, along with admin events and their details:

kcadm create realms -s realm=acme -s enabled=true \
  -s 'eventsListeners=["jboss-logging","webhook"]' -s adminEventsEnabled=true -s adminEventsDetailsEnabled=true

Then create a user, set a password, log in and get a password wrong, and watch docker logs -f webhook-receiver. In our test, every event arrived with a valid signature:

ActionWebhook received
Create userADMIN_CREATE with the full user record
Set passwordADMIN_ACTION (the password itself is never sent)
Log inLOGIN with client, IP address and grant type
Wrong passwordLOGIN_ERROR with invalid_user_credentials

Before you go to production

  • Don't lose events. sendAsync is fire-and-forget. If every event matters, add retries or an outbox and queue (Kafka, SQS).
  • Filter to the event types you need, and send the minimum personal data, because webhooks leave your identity system.
  • Use HTTPS, keep the secret in a vault and rotate it. Verify the signature with a constant-time compare.
  • Bake it into the image: copy the jar into /opt/keycloak/providers/ and run kc.sh build.

Keycloak webhook FAQ

Does Keycloak have webhooks built in?

No. Keycloak has event listeners, and webhooks are built on top of them with an extension like this one.

Do I need to turn on Save events?

No. Event listeners receive every event whether or not Save events is on. That setting only controls storing events in the database.

Will a slow receiver slow down logins?

No. The webhook is sent asynchronously after the transaction commits, so logins never wait for it.

Need an extension built, reviewed or hardened? We build and support Keycloak extensions for Australian organisations. Talk to us.

Talk to a Keycloak specialist

The first conversation is free.

Make an enquiry