How to revoke a user's session in SPI when group is updated via LDAP sync?

Hi all,

I’m developing a custom Keycloak EventListener SPI to handle the case when a user’s group membership changes, typically due to an LDAP sync (group mapping from LDAP to Keycloak).

My goal is:

  1. When a user is added to or removed from a group (GROUP_MEMBERSHIP with CREATE or DELETE),
  2. I want to:
  • Revoke all active sessions of that user,
  • Then apply custom group-to-group mapping logic.

The problem I’m facing is:
Although I can extract the userId from adminEvent.getResourcePath() (e.g., users/{userId}/groups/...), and the ID looks correct, session.users().getUserById(realm, userId) returns null.

Here’s the relevant part of my code:

String userId = extractUserId(adminEvent.getResourcePath()); // returns UUID
UserModel user = session.users().getUserById(realm, userId); // returns null
  • realm is correctly retrieved from session.realms().getRealm(realmId)
  • userId string seems valid (looks like a UUID)
  • But UserModel is always null, so I can’t revoke their sessions

Has anyone encountered this when working with admin events triggered by LDAP sync?
Is there a special context or timing issue where the user isn’t yet resolvable in the session?

Ultimately, I want this SPI to handle LDAP group sync changes and ensure that:

  • User sessions are revoked if group mapping changes
  • I can enforce a Rule-Based Group mapping mechanism

Thanks in advance for any help or insights!

Maybe your user is not yet mapped in Keycloak. In order to test that, test sync and then try:

When sync user will be visible in ‘users’ tab and mapped form keyclok.