RBAC in Spring Boot with Keycloak

Security is an important part of any microservice and implementing it on a Java Spring Boot application is easy thanks to Spring Security framework.

Spring Security provides a series of interfaces and implementations to help to authenticate and to authorise the requests on our applications. Thanks to this feature, creating an API that has a role based access control (RBAC) is a piece of cake.

What is Keycloak?

Keycloak is an open source IAM (Identity Access Management) that focuses on modern applications. It provides user federation, authentication, user management, authorisation..

Its features include:

  • Users authenticate with Keycloak: with this your applications don’t have to deal with login forms, authenticating users, and storing users. Once logged into Keycloak, users don’t need to login again to access a different application.
  • Enabling login with social networks is easy to add using the admin console.
  • Keycloak has built-in support to connect to existing LDAP or Active Directory servers. You can also implement your own provider.
  • Through the Admin console, administrators can centrally manage all aspects of the Keycloak server.

On top of this, the latest versions of Keycloak have been migrated to Quarkus making it optimised for cloud environments.

Why Keycloak?

Keycloak provides a nice catalogue of libraries for Java based applications, including Spring Boot support through keycloak-spring-boot-starter.

So we are able to use Keycloak as the authentication manager, where the users and passwords will be stored and the roles will be managed.

Configuration in Spring Boot applications

To use Keycloak as the authentication manager in Spring Boot with Spring Security we shall import the keycloak-spring-boot-starter dependency.

Here is the Maven example:

It is important to note that it’s best to use the same version number as the installed Keycloak server version to avoid compatibility issues. 

After this, we can create a configuration class that will allow us to use the spring boot configuration file instead of the keycloak.json file:

This is not really needed but it will allow for the application to look for the configuration on the Spring Boot application.yml file:

Now, the actual configuration needed for the Spring Boot application is just a small configuration class that extends from KeycloakWebSecurityConfigurerAdapter. It looks like this:

With all of these changes done, we can use Spring security to restrict access based on roles by annotating the application with @EnableGlobalMethodSecurity(prePostEnabled = true):

And then annotating the controller method calls: