Tuesday 22 December 2015

Creating users in keycloak using java API


Keycloak allows us to create users through admin console. But in few scenarios, we might not want our users to know about the underlying authentication mechanisms. In those scenarios, we may need to create users from our application, rather than opening up the admin console of keycloak.

In this post, let us discuss one such way to create users in keycloak by using java API’s.
Add the dependency below, to Maven pom.xml, in order to access the admin functions of Keycloak from the client.

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

In this post, we will see how to add users to the master realm. 
For this, we have to log into the realm as a user with admin privileges. We have a security-admin-console client, already defined which we are using for this example (But new client can be created and used based on the requirement). 

Keycloak kc = Keycloak.getInstance( "http://localhost:8080/auth", "master", "admin", “password",  "security-admin-console");

http ://localhost:8080/auth  Keycloak admin console url
master                  Realm to log in
admin                  user who has admin privilege in master realm
password                  password of admin user
security-admin-console  client to log in

Creating an existing user

After logging in using the above code, we can create a new user in the master realm

CredentialRepresentation credential = new CredentialRepresentation();
credential.setType(CredentialRepresentation.PASSWORD);
credential.setValue("test123");
UserRepresentation user = new UserRepresentation();
user.setUsername("testuser");
user.setFirstName("Test");
user.setLastName("User");
user.setCredentials(Arrays.asList(credential));
 user.setEnabled(true) ;
kc.realm("master").users().create(user);

User roles can be set using the following lines of code

user.setRealmRoles() ;
user.setClientRoles();

Updating an existing user

A specific user detail can be updated by fetching the user using user id from keycloak.

UserResource userResource = kc.realm("master").users().get("f20f524f-02f6-4465-bc7c-947f1ee9c3df");
UserRepresentation user = userResource.toRepresentation();
user.setFirstName("new First Name");
user.setLastName("new Last Name");
userResource.update(user);

Note : We could use the Admin REST API directly, instead of using java api, we will discuss the same in the next posts.
Thanks !! Meet you soon with next post !!

No comments:

Post a Comment