【问题标题】:Create keycloak client and assign role from other client programmatically以编程方式创建 keycloak 客户端并从其他客户端分配角色
【发布时间】:2019-11-19 15:29:24
【问题描述】:

我想创建新客户端,然后分配给该客户端角色“视图用户”,该角色由“领域管理”客户端拥有。 目标:我将能够通过这个新客户端列出用户。

我可以创建客户端,但不能为该客户端分配角色: 创建连接

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

然后我创建客户端

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

但是当我在创建客户端的过程中创建角色或稍后尝试分配它时,即使方法调用也不返回异常,也没有分配角色。

【问题讨论】:

    标签: java keycloak


    【解决方案1】:

    如果我需要服务帐户用户然后代表该用户分配角色,则棘手的部分。 另外,我花了很长时间创建的客户端具有相同的 ClientRepresentation.getId() 和 ClientRepresentation.getClientId() ('my-client') 但对于其他客户端可能完全不同,我需要 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()));
    

    【讨论】:

      猜你喜欢
      • 2017-08-30
      • 2018-09-08
      • 2019-10-19
      • 2018-09-23
      • 2021-01-03
      • 2010-12-11
      • 2017-09-12
      • 1970-01-01
      相关资源
      最近更新 更多