Skip to content

Instantly share code, notes, and snippets.

@jesuino
Created July 12, 2024 18:07
Show Gist options
  • Save jesuino/82089d21e3dd5674de2757d7727724bd to your computer and use it in GitHub Desktop.
Save jesuino/82089d21e3dd5674de2757d7727724bd to your computer and use it in GitHub Desktop.
Generating roles with Keycloak Java client
import static java.lang.System.out;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.representations.idm.GroupRepresentation;
public class GroupsCreate {
private static final String KEYCLOAK_HOST = "http://localhost:8080";
private static final String USERNAME = "wsiqueir";
private static final String PASSWORD = "test";
private static final String REALM = "master";
private static final String CLIENT_ID = "admin-cli";
private static final String CLIENT_SECRET = "2Dg5ErfaHPPzJQxVWfqZVq8wYpD6Hdb5";
private static final String TARGET_REALM = "rhdh";
private static final String TARGET_USER = "john";
private static final int TOTAL_GROUPS = 1000;
private static final String GROUP_PREFIX = "0_test_group_from_client";
public static void main(String... args) {
var keycloak = KeycloakBuilder.builder()
.serverUrl(KEYCLOAK_HOST)
.realm(REALM)
.username(USERNAME)
.password(PASSWORD).clientId(CLIENT_ID).clientSecret(CLIENT_SECRET).build();
var realm = keycloak.realm(TARGET_REALM);
// var groups = realm.groups();
var user = realm.users().search(TARGET_USER).get(0);
out.println("Groups will be added to user " + user.getUsername());
for (int i = 0; i < TOTAL_GROUPS; i++) {
var newGroup = new GroupRepresentation();
newGroup.setName(GROUP_PREFIX + "_" + i);
System.out.println("Adding group " + newGroup.getName());
realm.groups().add(newGroup);
// System.out.println("Adding group " + newGroup.getName() + " to user " +
// user.getUsername());
}
// keycloak.realm(TARGET_REALM).groups().add(groupRepresentation);
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>keycloak-groups-create</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-admin-client</artifactId>
<version>24.0.5</version>
</dependency>
</dependencies>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment