Keycloak: Working with realm roles in springboot

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

--

Before reading this story, please make sure that you have read my previous blog on how to add a user to a realm in spring boot which has the step by step guide on keycloak server setup.

https://medium.com/chain-analytica/keycloak-create-users-for-a-realm-in-spring-boot-3eff924a8db1

Please make sure that you have created your realm, your client and a realm admin. In this blog we will start with how to add new roles to a realm and how to add realm roles to the user using the admin console and we will see on how to do this programmatically in spring boot.

For getting some familiarity in some wordings let’s look at the following brief descriptions.

Realms: A realm is a management entity that manages a set of users, credentials, roles, and groups. A user belongs to and logs into a realm. Realms are isolated from one another and can only manage and authenticate the users that they control.

Roles: Roles are single or set of authorities that define the category of user. Frequently these roles are used for access controls on resources. So a role granted to a user is checked with the roles assigned to the resource of which the user trying to access.

Type of roles in keycloak: There are mainly two types of roles in keycloak. One is realm level roles and the other on is client level roles. The first one is global and shared by all clients belongs to the realm. The later one is mainly dedicated to a particular client. A role can be single or composite.

Composite roles: It is a role which has some other additional roles associated with it.

Okay, Lets start creating a role using keycloak admin console. Login to the admin console http://localhost:8080/auth/admin/ using your admin credentials. Switch to your realm using the dropdown on the upper left corner of the screen. Navigate to the roles tab using the Roles button on the left side navigation bar and click on “Add Role” button on the right most side, as shown in the picture below.

Add Role Button

In the next screen give a proper name and description(optional) and click on save.

Add new role

In the next screen you can specify whether you want this as a composite role or not. If you prefer to have a composite role, enable the switch corresponding to the composite roles label and in the Composite Roles section you can configure your role by adding one or more roles to it. In the below picture you can see that I have added a role named ‘offline-access’ to our newly created role to make it a composite role.

Composite role

Now let’s add this role to a user. For that, select the particular user from the “Users” tab in the left navigation bar and click on the id or click on the edit button corresponding to that user.

Find user

In the next screen navigate to the Role Mappings tab and select the role that we created, which is displayed in the Available Roles area and click on “Add selected” button to assign our new role to our user.

Assign role to the user

Until now we have been looking at creating and assigning realm roles using admin console; let’s look on how to do this in Spring Boot using keycloak admin client API.

Spring Boot application

Open your preferred browser, 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.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>

Let’s look below code snippet to get a clear understanding on how to get our keycloak instance.

    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";

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();
}

Let us now create a method to get all the available roles.

public List<String> getAllRoles(){  List<String> availableRoles = keycloak
.realm(realm)
.roles()
.list()
.stream()
.map(role -> role.getName())
.collect(Collectors.toList());
return availableRoles;
}

Now we will create a new role with a basic description to our realm.

public addRealmRole(String new_role_name){  if(!getAllRoles().contains(new_role_name)){     RoleRepresentation roleRep = new  RoleRepresentation();
roleRep.setName(new_role_name);
roleRep.setDescription("role_" + new_role_name);
keycloak.realm(realm).roles().create(roleRep);
}
}

We have created a new role to our realm. Now we shall look into how to get our new role as a Role Representation and make it a composite role by adding “offline_access” role to it.

public void makeComposite(String role_name){
RoleRepresentation role = keycloak
.realm(realm)
.roles()
.get(role_name)
.toRepresentation();
List<RoleRepresentation> composites = new LinkedList<>(); composites.add(keycloak
.realm(realm)
.roles()
.get("offline_access")
.toRepresentation()
);
keycloak.realm(realm).rolesById()
.addComposites(role.getId(), composites);
}

Note that you can add multiple roles to the list, For simplicity I have added only “offline_access”. Finally let us see how to assign a realm role to a user.

public void addRealmRoleToUser(String userName, String role_name)
String userId = keycloak
.realm(realm)
.users()
.search(userName)
.get(0)
.getId();
UserResource user = keycloak
.realm(realm)
.users()
.get(userId);
List<RoleRepresentation> roleToAdd = new LinkedList<>();
roleToAdd.add(keycloak
.realm(realm)
.roles()
.get(role_name)
.toRepresentation()
);
user.roles().realmLevel().add(roleToAdd);
}

Note that you can add multiple roles in one go by adding a list of roles into the RoleRepresentation list. So that's it, time for the conclusion.

In this post we have clearly discussed about how to create realm roles and how to add the created role to a user both by using admin console and also by using admin client API in spring boot. Hope you enjoyed it. Please don’t forget to give some clapping.

--

--