Keycloak: Create users for a realm in spring boot

Justus Nithushan
Chain Analytica
Published in
5 min readNov 10, 2020

Keycloak is an opensource IAM solution targeting the modern application and services. Keycloak provide many features including SSO, social login, authorization services, admin console, account management console and many more.

Before we move on to our main topic let us confirm that the keycloak server is up and running with some basic requirements. For that we will look into how to install a simple keycloak instance, create a admin user, create a realm and how to create a client. Let’s get started.

Download, install and start keycloak server

First of all download the keycloak server zip/tar file which contains all the scripts and binaries to run the keycloak server from https://www.keycloak.org/downloads

You can choose the file type according to your OS platform. The following image shows the file you want to download.

Once the download is completed, extract the file to your desired directory. Open a new command line interface and navigate to the bin directory and then run the ‘standalone’ bootscript to start the server.

Set up admin account

Once the server started without any error you can create an admin account. For that go to http://localhost:8080/auth and create an admin username and password. Once done, go to http://localhost:8080/auth/admin/ and login with your credentials. Now you can start creating realms.

Create realms

When you see the admin console it is clear that everything is fine up to now, so let’s focus our attention on the top left corner of the screen.

you can clearly see a beautiful blue color button popping up nicely when you hover your pointer over the master realm name, just press it. Give a preferred name of the realm and once you click saved, that's it we have created a new realm. Its time for setting up a client.

Setup client

In the realm we just created, navigate to ‘clients’ tab and click ‘create’ button on the right most side of the screen.

On the upcoming screen give your preferred client name and go on to the next screen by clicking on ‘save’ button.

In the next screen provide valid redirect uris which will need our new client for authentication purpose.

Make sure that the port of our spring boot application and the port we have given above are matching. Strengthen the security by configuring the client access type as confidential and click on save button. You can get a secret key by navigating to the credentials tab above and look for a disabled input box adjacent to the label named as ‘secret’.

So, finally we are on track to create our spring boot application to create a rest api that add user to the realm we created above.

Spring Boot application

Open your preferred browser and go to start.spring.io and create a new spring boot application. Make sure the following dependencies are added in pom.xml file.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-admin-client</artifactId>
<version>11.0.3</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.1.3.Final</version>
</dependency>

Feel free to add the version number you will be using in your project.

Let us create a User dto with some basic information. Here in this tutorial we will configure first name, last name, email and password for the new user.

public class User {
private String firstName;
private String lastName;
private String password;
private String email;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}

It is time to create a service which is nothing but a simple java class to get our keycloak instance. Lets name it as ‘KeyCloakConfig’. Make sure to change all the necessary variables below according to your project.

public class KeycloakConfig {

static Keycloak keycloak = null;
final static String serverUrl = "http://localhost:8080/auth";
final static String realm = "YOUR_REALM_NAME";
final static String clientId = "YOUR_CLIENT_ID";
final static String clientSecret = "YOUR_CLIENT_SECRET_KEY";
final static String userName = "YOUR_REALM_ADMIN_USERNAME";
final static String password = "Your_REALM_ADMIN_PASSWORD";

public KeycloakConfig() {
}

public static Keycloak getInstance(){
if(keycloak == null){

keycloak = KeycloakBuilder.builder()
.serverUrl(serverUrl)
.realm(realm)
.grantType(OAuth2Constants.PASSWORD)
.username(userName)
.password(password)
.clientId(clientId)
.clientSecret(clientSecret)
.resteasyClient(new ResteasyClientBuilder()
.connectionPoolSize(10)
.build();
)
.build();
}
return keycloak;
}
}

Lets create a new service which will have the functionality to create new user for the created realm. Lets name it as ‘KeycloakAdminClientService’. Note that here I have used the email as the username as every username must be unique.

public void addUser(User user) {   UsersResource usersResource = KeyCloakConfig.getInstance().realm(KeyCloakConfig.realm).users();    CredentialRepresentation credentialRepresentation = createPasswordCredentials(user.getPassword());

UserRepresentation kcUser = new UserRepresentation();
kcUser.setUsername(user.getEmail());
kcUser.setCredentials(Collections.singletonList(credentialRepresentation));
kcUser.setFirstName(user.getFirstName());
kcUser.setLastName(user.getLastName());
kcUser.setEmail(user.getEmail());
kcUser.setEnabled(true);
kcUser.setEmailVerified(false);
usersResource.create(kcUser);

}
private static CredentialRepresentation createPasswordCredentials(String password) {
CredentialRepresentation passwordCredentials = new CredentialRepresentation();
passwordCredentials.setTemporary(false);
passwordCredentials.setType(CredentialRepresentation.PASSWORD);
passwordCredentials.setValue(password);
return passwordCredentials;
}

Finally we will create our controller which defines an endpoint to create users.

@RestController
@RequestMapping
public class UserController {

@Autowired
KeycloakAdminClientService kcAdminClient;

@RequestMapping(value = "/user", method = RequestMethod.POST)
public UserRepresentation createUser(@RequestBody User user) {
return kcAdminClient.addUser(user);
}
}

That's it . We have now created a rest api to add users to our realm.

Hope you would have enjoy reading the story. Don’t forget to give some clapping.

Reference

Keycloak official:

--

--