Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a UserStorageProvider from java code

Tags:

realm

keycloak

I want to add a custom UserStorageSPI to Keycloak.

We can do it fro UI by selected it from dropdown under User-Federation -> Add Provider option, but we wanted to to do it from Java Code. We are trying to create an automated system where properties are picked up from YAML files and corresponding realms and clients are created automatically.

Keycloak keycloakClient = KeycloakBuilder.builder()
                             .serverUrl(authUrl)
                             .realm(StringUtils.defaultString(realm, "master"))     
                             .username(username)
                             .password(password)
                             .clientId(StringUtils.defaultString(client, "admin-cli"))
                             .resteasyClient(client)
                             .build();
    
keycloakClient.realms().create(realm);

This is a sample code that we are using to create a realm.
Looking for a similar way to add the UserStorageSPI

like image 489
pandeyk Avatar asked Nov 18 '25 23:11

pandeyk


1 Answers

You need ComponentRepresentation, which you can create with the following code:

private ComponentRepresentation createComponentRepresentation() {
    ComponentRepresentation cr = new ComponentRepresentation();
    cr.setName("your user storage provider id");
    cr.setProviderId("your user storage provider id");
    cr.setProviderType("org.keycloak.storage.UserStorageProvider");
    cr.setConfig(new MultivaluedHashMap<>());
    cr.getConfig().putSingle("cachePolicy", "DEFAULT");
    cr.getConfig().putSingle("priority", "10");
    cr.getConfig().putSingle("enabled", "true");
    cr.setParentId("your realm id");

    return cr;
}

And use keycloak client to create user federation on realm:

keycloakClient.realm("your realm id").components().add(createComponentRepresentation());
like image 64
Petro Mykhailyshyn Avatar answered Nov 21 '25 10:11

Petro Mykhailyshyn