Keycloak: Add Client Roles to Service Account Roles with Java API client

2.3k Views Asked by At

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

1

There are 1 best solutions below

3
On BEST ANSWER

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);