Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Keycloak Admin Client to create user with roles (Realm and Client level)
package demo.plain;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.CreatedResponseUtil;
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.UserResource;
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;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.Collections;
public class KeycloakAdminClientExample {
public static void main(String[] args) {
String serverUrl = "http://sso.tdlabs.local:8899/u/auth";
String realm = "acme";
// idm-client needs to allow "Direct Access Grants: Resource Owner Password Credentials Grant"
String clientId = "idm-client";
String clientSecret = "0d61686d-57fc-4048-b052-4ce74978c468";
// // 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 "idm-admin" 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 usersRessource = realmResource.users();
// Create user (requires manage-users role)
Response response = usersRessource.create(user);
System.out.printf("Repsonse: %s %s%n", response.getStatus(), response.getStatusInfo());
System.out.println(response.getLocation());
String userId = CreatedResponseUtil.getCreatedId(response);
System.out.printf("User created with userId: %s%n", userId);
// Define password credential
CredentialRepresentation passwordCred = new CredentialRepresentation();
passwordCred.setTemporary(false);
passwordCred.setType(CredentialRepresentation.PASSWORD);
passwordCred.setValue("test");
UserResource userResource = usersRessource.get(userId);
// Set password credential
userResource.resetPassword(passwordCred);
// // Get realm role "tester" (requires view-realm role)
RoleRepresentation testerRealmRole = realmResource.roles()//
.get("tester").toRepresentation();
//
// // Assign realm role tester to user
userResource.roles().realmLevel() //
.add(Arrays.asList(testerRealmRole));
//
// // Get client
ClientRepresentation app1Client = realmResource.clients() //
.findByClientId("app-frontend-springboot").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
userResource.roles() //
.clientLevel(app1Client.getId()).add(Arrays.asList(userClientRole));
// Send password reset E-Mail
// VERIFY_EMAIL, UPDATE_PROFILE, CONFIGURE_TOTP, UPDATE_PASSWORD, TERMS_AND_CONDITIONS
// usersRessource.get(userId).executeActionsEmail(Arrays.asList("UPDATE_PASSWORD"));
// Delete User
// userResource.remove();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.thomasdarimont.keycloak</groupId>
<artifactId>keycloak-admin-client-example</artifactId>
<version>1.0.0.0-SNAPSHOT</version>
<properties>
<keycloak.version>8.0.2</keycloak.version>
<resteasy.version>3.9.1.Final</resteasy.version>
</properties>
<dependencies>
<dependency>
<artifactId>keycloak-admin-client</artifactId>
<groupId>org.keycloak</groupId>
<version>${keycloak.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
</dependencies>
</project>
@dinohorvat

This comment has been minimized.

Copy link

dinohorvat commented Nov 23, 2017

Just one question. User and assigned roles can't be done in only one POST? Roles have to be assigned AFTER the user is created?
For instance if you send this JSON, roles won't be mapped (However, it worked in version 1.9):

{
    "username": "user11",
     enabled: true,
    "credentials": [{
    	"type": "password",
    	"value": "password"
    }],
    "realmRoles": ["employee"]
}
@Allan-Nava

This comment has been minimized.

Copy link

Allan-Nava commented Nov 29, 2017

Is possibile create user in http request with cURL o Postman?

@sanderdan

This comment has been minimized.

Copy link

sanderdan commented Dec 11, 2017

@dinohorvat: I'm having the same issue, did you manage to make any progress?
@Allan-Nava: Yes.

@marvinosswald

This comment has been minimized.

Copy link

marvinosswald commented Dec 19, 2017

@dinohorvat doesn't work with 3.3.0.CR2 either

@M3lkior

This comment has been minimized.

Copy link

M3lkior commented Feb 5, 2018

Hello @thomasdarimont,

Thanks for the Gist.

Your commented code (lines 27-34) is it working ? Are you tested the ADMIN API call with only an client-id (having the correct rights) ? (without the user/password requierement ?)

@SaatTek

This comment has been minimized.

Copy link

SaatTek commented Mar 5, 2018

hello,
i am trying to create user with this code but it gives an exception. "javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized"

just have one realm and its name is master.

Keycloak keycloak = KeycloakBuilder.builder() //
.serverUrl(serverUrl) //
.realm(realm) //
.grantType(OAuth2Constants.PASSWORD) //
.clientId(clientId) //
.clientSecret(clientSecret) //
.username("{username}") //
.password("{password}") //
.build();

user is the admin of the realm.
it gives exception in this line;
keycloak.realm("master").users().create(user);

actually it gives this exception all lines which trying to get somethind from keycloak.
for example : keycloak.realm("master").toRepresentation();

@n00bst3r

This comment has been minimized.

Copy link

n00bst3r commented Mar 21, 2018

Hi! Is there any reason you define the password credentials later by a separate request? I could also do that within the createUser request, couldn't I?

@thomasdarimont

This comment has been minimized.

Copy link
Owner Author

thomasdarimont commented Apr 19, 2018

In earlier versions of Keycloak you need to set the password via a separate requests since Keycloak 3.x one can create a user with password with a single request.

@ibmkhd

This comment has been minimized.

Copy link

ibmkhd commented Jun 24, 2018

@dinohorvat, @sanderdan same as you i tried the 4.0.0 final version.

@FlorianTolk

This comment has been minimized.

Copy link

FlorianTolk commented Jun 28, 2018

@vaishu-v

This comment has been minimized.

Copy link

vaishu-v commented Jan 22, 2019

Hello! Am trying to create user in keycloak by using this code. But am getting these error "realmResource.clients() - The method clients() is undefined for the type RealmResource and userRessource.get(userId).roles() .clientLevel(app1Client.getId()).add(Arrays.asList(userClientRole)) -
the method clientLevel(String) is undefined for the type RoleMappingResource". Help me to fix this error. Thanks in advance.

@borice

This comment has been minimized.

Copy link

borice commented Feb 11, 2019

Thanks for the code sample - this was very helpful.
How can we get the verification email flow triggered when creating a user via the admin API?

In the management interface, if the "Verify email" option is enabled in Realm Settings -> Login, when a user registers for an account, an email is sent to the user to verify their email address. I'm curious if it's possible to achieve the same for users created via the admin API.

Thank you.

@psloboda

This comment has been minimized.

Copy link

psloboda commented Apr 20, 2019

Is there a possibility to set Required actions to the user? In the realms we configured Accept Terms and Conditions as required action and email verification. Email verification can be set with userRepresentation.setEmailVerified(true) but configure that user Accept Terns and conditions with Rest API call to keycloak I do not found.

@ldqcuong

This comment has been minimized.

Copy link

ldqcuong commented Jul 30, 2019

Hi Guys,
I'm a newcomer, I'm trying to create a new user via Admin rest API, I have created some roles and assign it for my user as example mentioned as above (manage-users, view-clients, view-realm, view-users). My user is authenticated successfully but I cannot create user with response return is "403 Forbidden", this error may be related to Role or Permission. Currently, I'm using Keycloak version 6.0.1. Please help me!
Thanks in advance.

@diego-lipinski-de-castro

This comment has been minimized.

Copy link

diego-lipinski-de-castro commented Aug 13, 2019

Hi Guys,
I'm a newcomer, I'm trying to create a new user via Admin rest API, I have created some roles and assign it for my user as example mentioned as above (manage-users, view-clients, view-realm, view-users). My user is authenticated successfully but I cannot create user with response return is "403 Forbidden", this error may be related to Role or Permission. Currently, I'm using Keycloak version 6.0.1. Please help me!
Thanks in advance.

same here, any solution yet?

@matejko219

This comment has been minimized.

Copy link

matejko219 commented Aug 21, 2019

Hi Guys,
I'm a newcomer, I'm trying to create a new user via Admin rest API, I have created some roles and assign it for my user as example mentioned as above (manage-users, view-clients, view-realm, view-users). My user is authenticated successfully but I cannot create user with response return is "403 Forbidden", this error may be related to Role or Permission. Currently, I'm using Keycloak version 6.0.1. Please help me!
Thanks in advance.

same here, any solution yet?

Hi, I struggled with it for a few hours and I found solution for my problem. I am using service account for creating users and I had the same 403 response as you. I added "roles" client scope in my client settings. You must select your client then go to "Client Scopes" and add "roles" from "Default Client Scopes".

@norricorp

This comment has been minimized.

Copy link

norricorp commented Dec 4, 2019

Was there a solution to the javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized problem previously mentioned by @SaatTek? Same line of creating user (keycloak.realm(REALM).users().create(userRepresentation);)
I am using version 6.0.1. I have my own realm and am using the admin user and password.
Does KeycloakBuilder not authorise?
And the answer is it does not when the KeycloakBuilder object is created. It checks the credentials when it is used such as create. And to make it work, I needed the master user in the master realm. And then when creating, use the new realm.

@vtn

This comment has been minimized.

Copy link

vtn commented Dec 26, 2019

Very useful thank you

@martintw

This comment has been minimized.

Copy link

martintw commented Jan 9, 2020

FYI. The posted code no longer works with Keycloak 8.0.1. I was using Keycloak 6.0.1 and my create user code based on the above was fine.

Now it fails here:
userRessource.get(userId).resetPassword(passwordCred)
Simply throws a 400 BAD REQUEST with no error reporting - just a 400. Why is this??

@Meywether

This comment has been minimized.

Copy link

Meywether commented Jan 17, 2020

Hello everyone, thanks for this great example, I have a problem in my project with importing the dependencies, may I ask you to provide me the dependencies from your pom.xml ?
My maven install says, that org.keycloak.XXX can not be resolved? ( same for org.keycloak and so on, every package from the gist above!)

Thanks in advance!

@norricorp

This comment has been minimized.

Copy link

norricorp commented Jan 17, 2020

These are the keycloak entries I have for my Spring Boot 2 / keycloak project in the pom

....

org.keycloak
keycloak-spring-boot-starter

	<dependency>
		<groupId>org.keycloak</groupId>
		<artifactId>keycloak-admin-client</artifactId>
		<version>6.0.1</version>
	</dependency>

...

<dependencyManagement>
	<dependencies>

...

org.keycloak.bom
keycloak-adapter-bom
6.0.1
pom
import

...

Hope this helps

@Meywether

This comment has been minimized.

Copy link

Meywether commented Jan 17, 2020

Top thanks ! -> works so far. It seems my maven is broken ^^.
So just a second question -> This code can only be used on the client side, but would it be also possible to use it from the backend side?
Because I do not want to offer the credentials of a such powerful user to the client code side
Or is there another way to create keycloak user from spring server side?
Thanks in advance!

@norricorp

This comment has been minimized.

Copy link

norricorp commented Jan 19, 2020

Not sure what you mean. I have keycloak set up on the server. It is configured in the properties file and there are a few lines in the controller. So when I goto a protected resource, the keycloak login screen comes up. I also use keycloak java api to create a new keycloak user when a new user is created in the app. It was this that I commented on earlier with regard to the correct relam to use in KetcloakBuilder.
But there is nothing keycloak related in html / javascript.
And if I am using rest api, then the client code there does get a token and uses the keycloak server address.

@Meywether

This comment has been minimized.

Copy link

Meywether commented Jan 19, 2020

ah! Thanks! That was a missing link!

@norricorp

This comment has been minimized.

Copy link

norricorp commented Jan 20, 2020

which bit .....

@Meywether

This comment has been minimized.

Copy link

Meywether commented Jan 20, 2020

Two things:
1.) My misinformation about the frontend/backend code and 2.) the hint with the rest api.
I am pretty new to keycloak and OAuth :) So it is a really huge topic to work with keycloak.
Thanks a lot :)

@amr

This comment has been minimized.

Copy link

amr commented Feb 21, 2020

This is really cool, thanks. Small improvement:

Instead of:

String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");

You could do this:

UserResource user = keycloak.proxy(UserResource.class, response.getLocation());

Then use that directly like user.roles(), user.toRepresentation(), user.resetPassword(), etc.

@rdownie-dm

This comment has been minimized.

Copy link

rdownie-dm commented Feb 28, 2020

Is there a possibility to set Required actions to the user? In the realms we configured Accept Terms and Conditions as required action and email verification. Email verification can be set with userRepresentation.setEmailVerified(true) but configure that user Accept Terns and conditions with Rest API call to keycloak I do not found.

I'm having the same issue, any luck?

@AndreaNicola

This comment has been minimized.

Copy link

AndreaNicola commented Mar 2, 2020

You saved 1 Billion lives with this!!!

@AndresRamosC

This comment has been minimized.

Copy link

AndresRamosC commented Mar 2, 2020

You saved 1 Billion lives with this!!!

can you detail your POM file to see what dependencies are you using? I get
"this error com.fasterxml.jackson.jaxrs.cfg.AnnotationBundleKey.([Ljava/lang/annotation/Annotation;)V"

@thomasdarimont

This comment has been minimized.

Copy link
Owner Author

thomasdarimont commented Mar 2, 2020

I added the maven pom.xml with the proper dependency configuration.

@AndresRamosC

This comment has been minimized.

Copy link

AndresRamosC commented Mar 3, 2020

I'm getting error 403, I´m using the admin-CLI of my realm I can see that the session is being open but when I try to create the user I still get error 403,
image
image

as you can see i have with all the scopes and client scope
any ideas of that can it be?

@matejko219

This comment has been minimized.

Copy link

matejko219 commented Mar 3, 2020

@AndresRamosC I think you should create your own client for administration purposes. Then you should set its Access Type to confidential and enable Service Accounts setting. Client Scopes should be set as on your example. When you enable Service Accounts setting then new tab appears on configuration screen. In Service Account Roles tab you should set realm-management client roles like in your Scope tab.

@AndresRamosC

This comment has been minimized.

Copy link

AndresRamosC commented Mar 3, 2020

@AndresRamosC I think you should create your own client for administration purposes. Then you should set its Access Type to confidential and enable Service Accounts setting. Client Scopes should be set as on your example. When you enable Service Accounts setting then new tab appears on configuration screen. In Service Account Roles tab you should set realm-management client roles like in your Scope tab.

Thanks a lot, I did as you said and still got the 403 response, I had to change the line
Keycloak keycloak = KeycloakBuilder.builder() .serverUrl(serverUrl) .realm(realm) .grantType(OAuth2Constants.PASSWORD) .clientId(clientId) .clientSecret(clientSecret) .username("idm-admin") .password("admin") .build();
to ->
Keycloak keycloak = KeycloakBuilder.builder() .serverUrl(serverUrl) .realm(realm) .grantType(OAuth2Constants.CLIENT_CREDENTIALS) .clientId(clientId) .clientSecret(clientSecret) .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()) .build();
and finally got the response 201, thank you so much.

@chiragAcuver

This comment has been minimized.

Copy link

chiragAcuver commented Mar 6, 2020

I keep getting 400 Bad request whenever I use the "executeActionsEmail" for sending email.
Code
`
List actions=Arrays.asList(keycloakConfigs.getEMAIL_ACTIONS().split(","));

keycloakAdminClient
.realm(keycloakConfigs.getREALM())
.users()
.get(id)
.executeActionsEmail(keycloakConfigs.getCLIENT_ID(),keycloakConfigs.getEMAIL_REDIRECT_URI(),actions);
`

My Keycloak Server version : 8.0.1
My pom.xml :

`

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-webflux</artifactId>
<groupId>org.keycloak</groupId>

<artifactId>keycloak-admin-client</artifactId>

<version>8.0.1</version>
`
@chiragAcuver

This comment has been minimized.

Copy link

chiragAcuver commented Mar 9, 2020

I keep getting 400 Bad request whenever I use the "executeActionsEmail" for sending email.
Code
`
List actions=Arrays.asList(keycloakConfigs.getEMAIL_ACTIONS().split(","));

keycloakAdminClient
.realm(keycloakConfigs.getREALM())
.users()
.get(id)
.executeActionsEmail(keycloakConfigs.getCLIENT_ID(),keycloakConfigs.getEMAIL_REDIRECT_URI(),actions);
`

My Keycloak Server version : 8.0.1
My pom.xml :

`

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-webflux</artifactId>
<groupId>org.keycloak</groupId>

<artifactId>keycloak-admin-client</artifactId>

<version>8.0.1</version>

`

Stack overflow link for the same :
https://stackoverflow.com/questions/60596001/keycloak-java-admin-client-returns-400-error-on-triggering-verification-email

@norricorp

This comment has been minimized.

Copy link

norricorp commented Apr 25, 2020

@Tom534Tom

This comment has been minimized.

Copy link

Tom534Tom commented Apr 25, 2020

UsersResource usersResource = keycloak.realm(REALM).users(); Listkcusers = usersResource.list()
On 2020-04-25 12:06, Tom534Tom wrote: @Tom534Tom commented on this gist. ------------------------- Hi! Could you please tell me, how can I get all users? Like the " usersRessource.get(userId) " . I checked the usersRessource class, but I didn't find getAllUser. Thank you in advance. -- You are receiving this because you commented. Reply to this email directly, view it on GitHub [1], or unsubscribe [2].
Links: ------ [1] https://gist.github.com/c4e739c5a319cf78a4cff3b87173a84b#gistcomment-3269237 [2] https://github.com/notifications/unsubscribe-auth/AEUBLYOC6WTMD7KGQREQADTROK73FANCNFSM4HHJLT7A

thank you !

@gihanmaduranga

This comment has been minimized.

Copy link

gihanmaduranga commented Jun 21, 2020

This is very useful thanks for sharing the code snippet.While i am developing i also got the 401 Unauthorized Error this was due to as mentioned in the code comments i didn't have necessary user roles for my users. Eg: idm-client and idm-admin. to assign above users for roles follow the following instructions in keycloak admin console .

idm-client
clients -> select app client-> service account role tab-> type relam management under client roles -> assign nessary roles and save
idm-admin
users-> select admin user-> role mappings tab-> type relam management under client roles -> assign nessary roles and save

Hope this will help someone.

@Moataz-Hammous

This comment has been minimized.

Copy link

Moataz-Hammous commented Jun 22, 2020

Is there a way to create user group, then onboard these users on this user group ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.