javaspring-bootspring-data-jpakeycloak

How to support CRUD operations on user profile in Spring Boot when Keycloak manages user table?


I'm developing a Spring Boot application integrated with Keycloak for authentication and authorization. After reading this StackOverflow answer, I understand that the recommended approach is to not directly map Spring Boot entity tables with Keycloak's user_entity tables. Instead, I should maintain only a reference to the immutable user ID, similar to microservice architecture patterns.

My Challenge

However, my application requires comprehensive user profile CRUD operations (Create, Read, Update, Delete) for user-specific data. After further research, I discovered that Keycloak provides REST endpoints for user management, such as:

PUT /admin/realms/{realm}/users/{user-id}
GET /admin/realms/{realm}/users/{user-id}
POST /admin/realms/{realm}/users
DELETE /admin/realms/{realm}/users/{user-id}

My Approach

I'm thinking of implementing it like this:

  1. Spring Boot /profile endpoints for GET and PUT/PATCH.
  2. Internally, these endpoints would call Keycloak’s Admin REST API using a service client.
  3. Data would flow in and out via DTOs in my Spring Boot application—no direct JPA mapping to Keycloak tables.

Questions


Solution

  • You don't need Keycloak's Java libs for that. The OpenAPI specification of its admin API is enough.

    There are Spring generators for maven and gradle that you can configure to genere only @HttpExchange interfaces from an OpenAPI specification (carefully read the generator doc to work around the Keycloak's OpenAPI spec imperfections and to generate only the @HttpExchange interfaces).

    You can have Spring generate implementations ("proxies") from @HttpExchange interfaces.

    The only tricky part is to configure the RestClient or WebClient to provide to the @HttpExchange proxy factory. But I wrote a Boot starter that can be of great help, especially if you use the client credential flow and want token to be scoped to the application (Spring Security always scopes tokens to the user, even with the client credentials flow), or have to go through a proxy, or need to disable self-signed SSL certificate validation, ....