Integrating Keycloak with LDAP and external database: Best practices for user synchronization

Hey everyone,

I’m working on a project where we’re using Keycloak as our identity provider. We want to import LDAP users into Keycloak’s MySQL database and then sync all users (both local and LDAP) to our product’s separate MySQL database.

I’m not sure what’s the best way to handle this sync. Should we:

  1. Use the User Storage SPI and override GetUserByUsername?
  2. Create a custom Event Listener SPI and implement OnEvent?

My main concern is whether Keycloak triggers events when importing LDAP users. I know it does for local user updates, but I’m unsure about LDAP.

Has anyone tackled a similar setup? Any tips on the best approach for keeping our three data stores in sync would be super helpful. Thanks in advance!

I’ve dealt with a similar setup in the past, and I can share some insights. In our case, we found that using a custom Event Listener SPI was the most effective approach. We implemented the OnEvent method to capture user-related events, including LDAP synchronization.

To address your concern about LDAP import events, Keycloak does trigger events during LDAP synchronization, but they’re not as granular as local user events. We had to combine the Event Listener with periodic checks against the LDAP source to ensure complete synchronization.

One caveat: make sure your Event Listener is lightweight to avoid performance issues. We offloaded the actual synchronization to a separate service that processed events asynchronously.

Remember to thoroughly test your solution, especially for edge cases like network interruptions during synchronization. Good luck with your implementation!

hey, i’ve used keycloak with ldap. in my experince, the event listener spi works fine, but always add occasional ldap checks for edge cases. keep it simple and test well. best luck, friend.