Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create keycloak client and assign role from other client programmatically

Tags:

java

keycloak

I want to create new client and then assign to this client role 'view-users' which is owned by 'realm-management' client. Goal: I will be able to list users by this new client.

I am able to create client, but not to assign role to that client: Creating connection

public Keycloak keycloakAdmin() {
    return KeycloakBuilder.builder()
            .serverUrl("http://localhost:" + environment.getRequiredProperty("keycloak.port") + "/auth")
            .realm("master")
            .clientId("admin-cli")
            .username("admin")
            .password("password")
            .build();
}

Then I create client

ClientRepresentation encourageClient = new ClientRepresentation();
encourageClient.setId("my-client");
encourageClient.setSecret("password");
encourageClient.setDirectAccessGrantsEnabled(true);
encourageClient.setServiceAccountsEnabled(true);
keycloakAdmin.realm("my-realm").clients().create(encourageClient);

But when I create role during creation of client or when I try to assign it later, even method call does not return exception, role is not assigned.

like image 789
Cipous Avatar asked Dec 11 '25 15:12

Cipous


1 Answers

The tricky part if that I needed service account user and then on behalf of that user assign role. Also what took me long was that client I created had same ClientRepresentation.getId() and ClientRepresentation.getClientId() ('my-client') but those may be totally different for other client, and I needed getId()

RealmResource myRealm = keycloakAdmin.realm("my-realm");
    String userId = myRealm.clients().get("my-client").getServiceAccountUser().getId();
    UserResource serviceAccountUser = myRealm.users().get(userId);

    ClientRepresentation clientThatOwnsRole = myRealm.clients()
            .findByClientId("realm-management").get(0);

    String clientIdOfRoleOwner = clientThatOwnsRole.getId();
    ClientResource clientResourceOfRoleOwner = myRealm.clients().get(clientIdOfRoleOwner);
    RoleResource roleResourceToAssign = clientResourceOfRoleOwner.roles().get("view-users");

    serviceAccountUser.roles().clientLevel(clientIdOfRoleOwner).add(Collections.singletonList(roleResourceToAssign.toRepresentation()));
like image 97
Cipous Avatar answered Dec 13 '25 23:12

Cipous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!