Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Client programmatically in Keycloak

How do I create clients programmatically in keycloak using java application?

like image 379
Programmer Avatar asked Mar 29 '18 09:03

Programmer


3 Answers

One way to do it is via the api :

  • Get token for an account with the rights to add client to the realm

      POST https://<keycloak-url>/auth/realms/master/protocol/openid-connect/token
      Host: <keycloak-url>
      Content-Type: application/x-www-form-urlencoded
      Cache-Control: no-cache
    
      client_id=admin-cli&grant_type=password&username=<user>&password=<password>
    
  • Add a new client (the request body comes from an export of an existing client)

      POST https://keycloak-url/auth/admin/realms/<realm-name>/clients
      Host: <keycloak-url>
      Content-Type: application/json
      Cache-Control: no-cache
      Authorization: Bearer <token>
    
      {
           "clientId": "test-add",
           "[...]"
       }
    

The response status should be a 201 with an header location to the new client.

Documentation can be found here : https://www.keycloak.org/docs-api/14.0/rest-api/index.html#_clients_resource

like image 152
Cédric Couralet Avatar answered Oct 22 '22 02:10

Cédric Couralet


I did it like this,

public boolean createClient(String clientId, String realmName) throws IOException {
    try {
        Keycloak keycloakInstanceDefault = KeycloakInstance.getInstance();
        RealmResource createdRealmResource = keycloakInstanceDefault.realms().realm(realmName);
        ClientRepresentation clientRepresentation = new ClientRepresentation();
        clientRepresentation.setClientId(clientId);
        clientRepresentation.setProtocol("openid-connect");
        clientRepresentation.setSecret(clientId);
        createdRealmResource.clients().create(clientRepresentation);

    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

KeycloakInstance.getInstance(); returns Keycloak Object.

like image 33
Gökhan Ayhan Avatar answered Oct 22 '22 02:10

Gökhan Ayhan


Using curl

#get token
RESULT=`curl --data "username=<your_admin_user>&password=<your_passwod>&grant_type=password&client_id=admin-cli" http://localhost:8090/auth/realms/master/protocol/openid-connect/token`
TOKEN=`echo $RESULT | sed 's/.*access_token":"//g' | sed 's/".*//g'`
#create user
curl -X POST -d '{ "clientId": "myclient" }' -H "Content-Type:application/json" -H "Authorization: bearer ${TOKEN}" http://localhost:8090/auth/realms/master/clients-registrations/default
like image 2
Elieser Jose Pereira Reyes Avatar answered Oct 22 '22 04:10

Elieser Jose Pereira Reyes