Enable/Disable Eventlistener for Keycloak


I have implemented a new Keycloak extension using Keycloak Eventlistener SPI.
I have some queries regarding Eventlistener implementation.

in the init() method of EventListenerProviderFactory, I am implementing some logic that access the Keycloak DB and do some operation.

I have not provided any implementation to onEvent() methods from eventListenerProvider interface as I don’t want my logic to do anything when events are occurred.

now, when I run this extension with Keycloak irrespective of enable/disable (from keycloak ui) state of this listener, the logic implemented in init() method of EventListenerProviderFactory() is executing. My understanding is, init() method executes only once when we enable the eventListener from the UI and it should not execute if the eventListener is disabled.

how should I make it work in correspondence with enable/disable Eventlistener?

any help will be appreciated.

init() gets called when the ProviderFactory is first created. This has nothing to do with whether or not the event listener is enabled. I don’t believe there are currently hooks available to know if an event listener has been enabled or disabled.

It’s a bit of a hack, but I suppose you could create an event listener that watched admin events of operationType=UPDATE, and resourcePath=events/config and then look at the representation to see if the event listener you are interested in was added/removed.

However, the whole thing seems like a bit of a hack. Why are you using the event listener SPI for this if you’re not interested in events? Do you just want a way to run something in a one-off basis?

@xgp I want to run a scheduler on periodic basis to do certain operations in Keycloak database. and I also want to provide an option to enable or disable this scheduler. hence I thought I should use Eventlistener SPI so that enabling/disabling Eventlistener from Keycloak UI will help me in certain way. But it looks like init() method from factory is executing irrespective of enabling/disabling of Eventlistener. DO you know any other way that I can use to implement this?

I’m not aware of a way to enable/disable things like this using any facility in Keycloak. You could add a JPA entity with a single row (enabled or disabled) in the DB that your scheduled task queried before running.

Also, something I have done before to store some config (or a flag) in the DB is to use Realm attributes. This allows you to update them using the Admin API (Keycloak Admin REST API) and you won’t have to add a custom JPA entity. You could store your enabled/disabled flag as a Realm attribute, and then have your scheduled task check it before executing. That should do what you want.

@xgp. Thanks a lot, this seems doable. I will try it