How do I create clients programmatically in keycloak using java application?
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
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.
#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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With