Search code examples
javajbosskeycloakkeycloak-services

Keycloak Create Client


I'm trying to create a new Keycloak client using the keycloak-admin-client.

Here's my code:

        Keycloak keycloak =
                KeycloakBuilder.builder()
                        .serverUrl("http://localhost:8080/auth")
                        .realm("realm-name")
                        .grantType(OAuth2Constants.PASSWORD)
                        .username("admin")
                        .password("adminPassword")
                        .clientId("admin-cli")
                        .resteasyClient(new ResteasyClientBuilderImpl().connectionPoolSize(10).build())
                        .build();

        ClientRepresentation clientRep = new ClientRepresentation();
        clientRep.setClientId(clientId);
        clientRep.setSecret(UUID.randomUUID().toString());
        clientRep.setProtocol("openid-connect");

        keycloak.realm("realm-name").clients().create("test-client");

When doing this, I get an unauthorized error (javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized), but I know my admin password is correct.

My use case is that I am using the main Keycloak admin. I need to be able to set up a realm, client, and user (and then some configurations) using only the client API and without any manual steps. I'm needing to set up a completely automated Keycloak setup for the sake of a Dockerized CI/CD build.

It's worth noting that I'm not needing this to be the most secure strategy. I'm just wanting to write some code that I can use to automate setting up a Dockerize Keycloak instance for some tests.


Solution

  • In this part:

    Keycloak keycloak =
                    KeycloakBuilder.builder()
                            .serverUrl("http://localhost:8080/auth")
                            .realm("realm-name")
                            .grantType(OAuth2Constants.PASSWORD)
                            .username("admin")
                            .password("adminPassword")
                            .clientId("admin-cli")
                            .resteasyClient(new ResteasyClientBuilderImpl().connectionPoolSize(10).build())
                            .build();
    

    instead of .realm("realm-name") use .realm("master")