5

I want to add client roles for a service account for an existing Keycloak client (service user is enabled on this client). I have managed to do this via the web panel (see screenshot).

However, I need to do this role assignment using Keycloak Java API client. I know how to connect the client and the general functionality of the Keycloak Java client.

Specifically, I want to add the client roles realm-management.view-users and realm-managment.query-users to the service account of the client "platform-administration".

Screenshot from Keycloak web panel

André
  • 464
  • 4
  • 17

1 Answers1

12

Okay I figured it out myself. What really helps, if you don't know how the API functions are, is to open the Developer Console of the browser, open the Keycloak web panel, perform the actions and then look at the API calls in the network tab.

RealmResource realm = keycloak.realm("realmName");

String realmManagementId = realm.clients().findByClientId("realm-management").get(0).getId();

String platformAdministrationId = realm.clients().findByClientId("platform-administration").get(0).getId();

String serviceUserId = realm.clients().get(platformAdministrationId).getServiceAccountUser().getId();

List<RoleRepresentation> availableRoles = realm.users().get(serviceUserId).roles().clientLevel(realmManagementId).listAvailable();

List<RoleRepresentation> rolesToAssign = availableRoles.stream().filter(r -> "view-users".equalsIgnoreCase(r.getName()) || "query-users".equalsIgnoreCase(r.getName())).collect(    Collectors.toList());
realm.users().get(serviceUserId).roles().clientLevel(realmManagementId).add(rolesToAssign);
André
  • 464
  • 4
  • 17
  • 4
    Thank you. A life saver. If I'd ever need to turn some devs life into a nightmare I'd do stuff like it is in keycloaks API ]:-> – denu Jul 28 '22 at 10:33
  • 1
    Glad I could help. Thanks for the feedback. Yes, the Keycloak Api is ... well, let's say, something special :D Many detours and unclear procedures to get and process information. – André Aug 12 '22 at 09:23
  • Did some digging myself, and came across this: https://medium.com/chain-analytica/keycloak-working-with-realm-roles-in-springboot-dc2776ccd27e but specifically for Keycloak and Spring together. I used a combination of the article and your solution. – Beast Feb 14 '23 at 14:57