Keycloak, clients and roles: a tutorial

Tomas Pinto
8 min readJan 18, 2022

--

Photo by Angela Merenkova on Unsplash

Keycloak is an open-source Identity and Access Management solution making easy to secure applications and services with little to no code.
This tutorial explains how Keycloak works and its mechanism using a simple ReactJS code.

What is Keycloak?

Users authenticate with Keycloak rather than individual applications. That means that your applications don't have to deal with log-in forms, authenticating and storing users.

Keycloak supports standard protocols for authorization and authentication as OAuth 2.0, OpenID Connect SAML. You can choose which mechanism you want to use to secure your application. If you wish, you can also choose to secure some with OpenID Connect and others with SAML.

The code used by this tutorial

This tutorial aims to give you a brief introduction to Keycloak and its mechanism using a simple ReactJS code.

A docker-compose file runs an instance of the Keycloak server used by the React component application.

Moreover, there is a JSON file named realm-keycloak-tutorial.json. You can import this configuration file into the running Keycloak server, which recovers the setting I used to run the project. Moreover, I will explain how to set a configuration up step by step.

Installation

Keycloak offers different ways to start. I decided to go with Docker in this tutorial; I have already prepared a docker-compose file.
Feel free to choose any other installation.
Hence, to run the Keycloak server, type on a shell: docker-compose up -d
Then, open the browser, go to http://localhost:8080. You will be redirected to the admin console page.

Click on "Administration console". Log in with user admin and password admin. (Do not use this in production! :D)

The Keycloak server

Once you log in, Keycloak shows you the Master realm.

A realm 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.
(www.keycloak.org)

Now we need to set up the realm for our application. Let's click on the button "Add realm".

Name the new realm "keycloak-tutorial" and click on "create".

We created a new realm!

Create the client

In Keycloak, applications or services you want to secure are named clients.

Clients are entities that can request Keycloak to authenticate a user. Most often, clients are applications and services that want to use Keycloak to secure themselves and provide a single sign-on solution. Clients can also be entities that just want to request identity information or an access token so that they can securely invoke other services on the network that are secured by Keycloak.
(www.keycloak.org)

Keycloak grants human users permission to provide a username and password; anyway, a "non-human user" could call the API exposed by another application secured with Keycloak.

In the menu on the left, click on "Clients", then click on "create" on the bottom right of the table.
Now fulfil the form with the parameters of our application:

Creating the client named "my-react-client".

Clicking on "save", Keycloak shows you the setting page of "my-react-client", where we define our client's address and port.

We are setting the client up.

Set the URL of the application as http://localhostt:3000.
Click on the "save" button, and our client is ready!

The roles

Now it's time to define the roles for our application. Each role will have different "power" in our application.

Roles identify a type or category of user. Admin, user, manager, and employee are all typical roles that may exist in an organization. Applications often assign access and permissions to specific roles rather than individual users as dealing with users can be too fine-grained and hard to manage.
(www.keycloak.org)

Keycloak has roles for the whole realm or a specific client. In our tutorial, we specify roles for our Keycloak client.

From the client's page, click on the tab named "Roles", and then click on the button "create".

The role is named "manager".

We define two roles: "manager" and "user". Once all the roles are ready, we can see the list of the available roles for the client:

List of the roles available in "my-react client."

Creating users and assigning roles

Let's create the users.

Users can have attributes associated with themselves like email, username, etc. In addition, they can be assigned group membership and have specific roles assigned to them.

On the menu on the left, in the "Manager" section, click on "User".

The user section of Keycloak

Now click on the "Add user" button to create the user user@acme.com as in the picture below.

Once the user profile is completed, go back to the Users page.

Let's edit the profile and assign a role to the user by clicking on the tab "Role Mappings". We want to give the role "user" from the client's roles list to this user.

As you can see, we are using a role specifically for that client. However, it is possible to have client roles with broad scope and share them between different clients.

[…] creating new clients easier by sharing some common settings. This is also useful for requesting some claims or roles to be conditionally based on the value of scope parameter. Keycloak provides the concept of a client scope for this.
(www.keycloak.org)

Select the client "my-react-client" and pick the role user.

The current user has an assigned role named "user".

Creating the user profile named manager@acme.com with role manager required the same steps. The profile manager@acme.com has as assigned role "manager".

Roles assigned to the user manager@acme.com.

By the tab "Roles" from the client's page, we can check if the role assignment succeed:

Creating the app

Now that we have set up the Keycloak server, we can focus on the ReactJS app. The application we are creating is a simple website with four pages:

  • Welcome: it is a welcome page that doesn't require any log-in
  • Public: it is a page that does not require any log in
  • Manager: Only users who have the role "manager" can access it. This page contains a simple HTML table with a list of employees.
  • User Details: Only users who have "manager" or "user" can access it. That page shows some information about the logged user. The page gets the user's data from the KeyCloak token.

Keycloak configuration

Keycloak offers different adapters to secure your software.
Adapters are libraries integrating your software with Keycloak and reducing the boilerplate code. For example, this tutorial uses the client-side JavaScript library to install the npm package keycloak-js.

We defined a function named useKeyCloak to get the token from the Keycloak server if the user is authenticated successfully.

Let's take a close view of the code.

In line 3, it imports the Keycloak js library :

import Keycloak from 'keycloak-js'

That is the JSON configuration (you can find it in the tutorial code or export it from Kycloak)of the client we have set before:

Then we import it into the project, then pass it to the Keycloak library's function :

var keycloak = Keycloak(‘/keycloak.json’)

The keycloak object has all the information needed to verify and authorize every request to the client named "my-react-client".

In line 8, we use a ReactJs Hook, so every time a page is rendered Keycloak library connects to the Keycloak server, using the JSON settings, checking:

  • if a keycloak token is available (user already logged in); which contains roles and other information about the user
  • If not, it requires the user to log in.

Secure the page with roles

The next step is to secure pages "Manager" and "User details" and grant access only to users with a specific role.
The user needs to have the role "manager" to access the Manager page, as described in the previous steps.

To do so, I imported the function useKeyCloak into Maganer.js:

In line 2, the function UseKeycloak is imported. Then at line 9, we check if the user has the role manager, using the constant keycloak created at line 5.
In line 33, we check if the keycloak constant is not null, perhaps the log-in failed, or if the user has no proper role, we show a message of access denied.

The same mechanism is in place for UserDetails.js, as shown below.

The only difference with Manager.js is that users need a "manager" or "user" role to access the UserDetails page.

Conclusion

This tutorial showed how to secure a ReactJS application using Keylcoak.
We learned how to configure the Keycloak server and create a client with two users with different roles.

Keycloak offers adapters for different languages and platforms, like Javascript, Node.js, SpringBoot, etc.
Secure each page with a specific role in Java and Spring boot is slightly different from what we did with ReactJS. However, the concept of binding a resource to a role is the same no matter the adapter is used.

Using Keycloak, it is easy to set up quickly roles and users and let Keycloak secure the application so developers can focus on the business logic.

You can find the code shown in this tutorial on my GitHub page.

Thank you for reading, see you soon.

--

--

Tomas Pinto

I’m not a nerd, maybe a geek. I like to write code, stories and stories about code. motnip@github| motnip@twitter