Reputation: 3374
I am building a REST API with spring boot and for authentication and authorization I am using Keycloak. Since the users are managed by Keycloak, my application database does not have the data of the users. But I want to store some attributes of the User entity from Keycloak in my application database, as user data will be required for audit purposes.
So what would be the best way to synchronize the application database User table with keycloak User table?
Upvotes: 5
Views: 4719
Reputation: 3721
I would implement a Keycloak plugin based on the EventListenerSpi. In the EventListenerProvider implementation you can concentrate on the user administration events only.
public class SyncEventListener implements EventListenerProvider
{
private static final List<OperationType> SYNC_OPERATIONS = Arrays.asList(OperationType.CREATE, OperationType.UPDATE, OperationType.DELETE);
@Override
public void close() {}
@Override
public void onEvent(Event event) {}
@Override
public void onEvent(AdminEvent event, boolean includeRepresentation)
{
if ((event.getResourceType() == ResourceType.USER) && SYNC_OPERATIONS.contains(event.getOperationType()) )
{
// Write user data to external message queue or database
externalStore.write(event.getOperationType(), event.getRepresentation());
}
}
}
The event.getRepresentation() returns a JSON object with all user data. Of course you have to turn on admin events via Keycloak admin console (Events/Config/Admin Events Settings) to make this work. Put both "Save events" and "Include Representation" to ON.
Upvotes: 5