Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyCloak - Create Realms/Users/Groups Programmatically?

We've decided to move to KeyCloak for our identity and access management solution, rather than implement it entirely within our Java EE web app. We're creating a multi-tenant solution, and would prefer to create security realms/users/groups programmatically through our workflow, rather than leveraging KeyCloak's self-registration functionality or web UI so that we can do things like grab credit card details for payment, etc. I know that we could likely leverage the admin REST APIs to accomplish this, but I wasn't sure if there was a simpler way to do it besides hand-coding REST calls. Does KeyCloak provide an admin client library that we could use? Or are we stuck implementing a REST client for the admin APIs ourselves?

like image 839
Shadowman Avatar asked Jul 25 '18 14:07

Shadowman


2 Answers

I found some info around the KeyCloak Java Admin Client. This gist has lots of useful examples showing how to managed users, realms, etc.

like image 125
Shadowman Avatar answered Oct 13 '22 02:10

Shadowman


Keycloak kc = KeycloakBuilder.builder() 
            .serverUrl("https://localhost:8443/auth")
            .realm("master")
            .username("admin") 
            .password("admin") 
            .clientId("Mycli") 
            .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()) 
            .build();

    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue("test123");

    UserRepresentation user = new UserRepresentation();
    user.setUsername("testuser2");
    user.setFirstName("Test2");
    user.setLastName("User2");
    user.setEmail("[email protected]");
    user.setCredentials(Arrays.asList(credential));
    user.setEnabled(true);
    user.setRealmRoles(Arrays.asList("admin"));

    // Create testuser
    Response result = kc.realm("my-realem").users().create(user);
    if (result.getStatus() != 201) {
        System.err.println("Couldn't create user.");
        System.exit(0);
    }else{
        System.out.println("Testuser created.... verify in keycloak!");
    }
like image 43
Nan Avatar answered Oct 13 '22 02:10

Nan