Extending core addUser and removeUser functionality

I want to add functionality to the core addUser and removeUser functions. From what I understand, I can write a new UserStorageProvider in order to allow federation with other platforms. That’s not what I want to do, though - I want to add some extra code that runs when the built-in addUser and removeUser functions are called. Is there a way to do this with the SPI or extensions?

There aren’t great ways to do this that I’m aware of. It has been proposed to have a better event model for these types of changes, but I don’t know where they are in development.

You can execute code on user removed by registering a ProviderEventListener in the KeycloakSessionFactory. E.g.:

  @Override
  public void postInit(KeycloakSessionFactory factory) {
    factory.register(
        (event) -> {
          if (event instanceof UserModel.UserRemovedEvent) {
            // do your handler here
          }
        });
  }

For user added, you can write an EventListener that watches the REGISTER event, but that won’t catch all of the cases (e.g. an admin adds a user through the admin UI). You’d also have to watch for admin events for CREATE on UserResource, but I’m not sure if those two would be comprehensive.

1 Like

Perfect! Thank you, @xgp - it took me a little while to remember my Java, but once I did, this worked like a charm!