Search code examples
javakeycloakkeycloak-services

Keycloak: how to programmatically add new subgroups with associated users?


In Keycloak 8.0.1 we have a Realm with a Group and Subgroups like this:

group -
    subgroup1
    subgroup2
    ...

We need to insert a batch of subgroups and users into group. The subgroup should have some attributes.

How can I do this?

I tried:

  1. Using an exported realm-export.json file with newly added subgroups and "Overwrite" on the import. Now I don't see how to connect the new user with the subgroup. And I am also not sure if old users will not be removed this way.

  2. Calling the Keycloak REST API. It doesn't seem possible to UPDATE a group and add subgroups. Documentation says:

    PUT /{realm}/groups/{id}
    Update group, ignores subgroups.

Now I am looking at using a UI testing tool to add the user programmatically, but this seems needlessly complex.

Is it possible to programmatically add new subgroups with users associated to that subgroup? Am I missing something with the REST API call or the import functionality? Is there maybe another way via for example the Java Admin Client?


Solution

  • You can create groups and subgroups under it , Here is the sample code to create subgroups using Admin Client. You can also associate users to those groups

     public void addSubgroups()  {
                RealmResource realm =keycloak.realm("myrealm");
                GroupRepresentation topGroup = new GroupRepresentation();
                topGroup.setName("group");
                topGroup = createGroup(realm, topGroup);
    
                createSubGroup(realm,topGroup.getId(),"subgroup1");
                createSubGroup(realm,topGroup.getId(),"subgroup2");
            }
    
           private void createSubGroup(RealmResource realm, String parentGroupId, String subGroupName) {
               GroupRepresentation subgroup = new GroupRepresentation();
                 subgroup.setName(subGroupName);
               try (Response response = realm.groups().group(parentGroupId).subGroup(subgroup)){
                    if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
                        System.out.println("Created Subgroup : " + subGroupName );
                    } else {
                        logger.severe("Error Creating Subgroup : " + subGroupName + ", Error Message : " + getErrorMessage(response));
                    }
                } 
           }
    
           private GroupRepresentation createGroup(RealmResource realm, GroupRepresentation group) {
                try (Response response = realm.groups().add(group)) {
                    String groupId = getCreatedId(response);           
                    group.setId(groupId);
                    return group;
                }
            }