Keycloak - How to get all users for a realm and save them to application database?

牧云@^-^@ 提交于 2019-12-11 16:06:01

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/47018791/keycloak-how-to-get-all-users-for-a-realm-and-save-them-to-application-databas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!