Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Created June 7, 2017 19:56
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save thomasdarimont/0c136d0b8d339b997928e9bef225f941 to your computer and use it in GitHub Desktop.
Save thomasdarimont/0c136d0b8d339b997928e9bef225f941 to your computer and use it in GitHub Desktop.
Simple example for creating a User with Keycloaks Admin Client - with credentials, custom roles, and user attributes
package de.tdlabs.keycloak.client;
import java.util.Arrays;
import java.util.Collections;
import javax.ws.rs.core.Response;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UsersResource;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
public class KeycloakAdminClientExample {
public static void main(String[] args) {
String serverUrl = "http://sso.tdlabs.local:8899/u/auth";
String realm = "javaland";
String clientId = "idm-client";
String clientSecret = "a200cdf6-ad72-4f6c-af73-5b8e1cc48876";
// // Client "idm-client" needs service-account with at least "manage-users, view-clients, view-realm, view-users" roles for "realm-management"
// Keycloak keycloak = KeycloakBuilder.builder() //
// .serverUrl(serverUrl) //
// .realm(realm) //
// .grantType(OAuth2Constants.CLIENT_CREDENTIALS) //
// .clientId(clientId) //
// .clientSecret(clientSecret).build();
// User "javaland" needs at least "manage-users, view-clients, view-realm, view-users" roles for "realm-management"
Keycloak keycloak = KeycloakBuilder.builder() //
.serverUrl(serverUrl) //
.realm(realm) //
.grantType(OAuth2Constants.PASSWORD) //
.clientId(clientId) //
.clientSecret(clientSecret) //
.username("idm-admin") //
.password("admin") //
.build();
// Define user
UserRepresentation user = new UserRepresentation();
user.setEnabled(true);
user.setUsername("tester1");
user.setFirstName("First");
user.setLastName("Last");
user.setEmail("tom+tester1@tdlabs.local");
user.setAttributes(Collections.singletonMap("origin", Arrays.asList("demo")));
// Get realm
RealmResource realmResource = keycloak.realm(realm);
UsersResource userRessource = realmResource.users();
// Create user (requires manage-users role)
Response response = userRessource.create(user);
System.out.println("Repsonse: " + response.getStatusInfo());
System.out.println(response.getLocation());
String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");
System.out.printf("User created with userId: %s%n", userId);
// Get realm role "tester" (requires view-realm role)
RoleRepresentation testerRealmRole = realmResource.roles()//
.get("tester").toRepresentation();
// Assign realm role tester to user
userRessource.get(userId).roles().realmLevel() //
.add(Arrays.asList(testerRealmRole));
// Get client
ClientRepresentation app1Client = realmResource.clients() //
.findByClientId("app-javaee-petclinic").get(0);
// Get client level role (requires view-clients role)
RoleRepresentation userClientRole = realmResource.clients().get(app1Client.getId()) //
.roles().get("user").toRepresentation();
// Assign client level role to user
userRessource.get(userId).roles() //
.clientLevel(app1Client.getId()).add(Arrays.asList(userClientRole));
// Define password credential
CredentialRepresentation passwordCred = new CredentialRepresentation();
passwordCred.setTemporary(false);
passwordCred.setType(CredentialRepresentation.PASSWORD);
passwordCred.setValue("test");
// Set password credential
userRessource.get(userId).resetPassword(passwordCred);
}
}
@Allan-Nava
Copy link

How can I implement this class in my Keycloak?

Thanks

@Neeo22
Copy link

Neeo22 commented Apr 14, 2021

Thanks a lot!

@jfrantzius
Copy link

Thx for the example, in later Keycloak versions the URL seems to be different, see https://stackoverflow.com/a/71634718: /realms/{realm}/protocol/openid-connect/token , without the /auth prefix

Using https://github.com/Huachao/vscode-restclient I verified it like this:

# test Keycloak authentication for admin-cli client
# use https://github.com/Huachao/vscode-restclient/blob/master/README.md VS Code extension

# effectively tests what org.keycloak.admin.client.token.TokenService.grantToken(String, MultivaluedMap<String, String>) does
POST http://localhost:9090/realms/master/protocol/openid-connect/token 
Content-Type: application/x-www-form-urlencoded

grant_type=password
&username=admin
&password=admin
&client_id=admin-cli

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment