microservice Security using Keycloak (source)

In my previous blog, we have gone through the basic understanding of Microservices and what all the important components that are involved in modern application security like OAuth, OpenID, and JWT etc.

In this final series of Microservices and Security, we will go through Keycloak, which is an open source identity and access management solution by RedHat and we will also see how to include keycloak in our microservice’s security module, specifically spring-boot based microservices.

About Keycloak :

As said above, Keycloak is an open-source identity and access management solution for modern services and applications.

Keycloak also secured its place in ThoughtWorks Tech Radar this year.

It offers useful features of identity and access management:

single-sign-on (SSO), identity brokering and social login

user federation

client adapters

admin console and account management console.

To learn more about Keycloak’s features, click here.

features of Keycloak (source)

Although security is an essential aspect of any application, the implementation part of security is complicated and difficult. In general, it is often neglected or poorly implemented and intrusive in the code.

Developers desire security servers which allow for the outsourcing and delegation of authentication and authorization aspects. They want a tool that automates the development of security features for applications, which is generally a complex task.

Keycloak is one of the most promising open-source IDAM (Identity and Access Management) servers, which is agnostic of any technology and can easily deploy/adapt in its own infrastructure.

Keycloak tries to solve single sign-on for web apps and web services that are REST-based. The ultimate goal of Keycloak is to make security simple enough so that it plugs in as a security module in services and apps. Security features are messy, and when developers manually have to write for themselves, it becomes riskier and more error-prone. Keycloak helps us by providing security features out of the box and is easily customizable to the individual requirements of any organization.

Keycloak can help us introduce these features in an application:

customizable user interfaces for login, registration, administration, and account management

integration to existing LDAP and active directory servers

delegate authentication to third-party identity providers like Twitter and Github

The project is open source and can be found on Github.

Installation:

There are different ways to install keycloak. The simplest is to just download Keycloak, which is a standalone mode of installation and just unzip it. You’re done! Now open a terminal and go to your unzipped Keycloak server and navigate to the bin directory — and simply run the following command:

./standalone.sh(bat)

More details on installation can be found here in the Installation Guide.

After installation, open a browser and go to http://localhost:8080/auth.

By default, Keycloak comes with an H2 database, but if you opt for RDMS you can go with Keycloak with RDMS.

Since you are running the server for the first time, you will have to create an admin user. Let’s create an admin user with ‘admin’ as the username and ‘admin’ for the password:

very first UI in Keyclaok

Creating a New Realm

In Keycloak, a realm is a place where you will define your clients. This means an application that will be secured by Keycloak — probably a web application or a Spring Boot.

Note: ‘Master’ is the default realm in Keycloak.

Let’s create a new realm by simply clicking the “Add realm” button:

adding Realm

Creating the Client

Your Spring Boot application is your client. It’s that simple. In Keycloak, the client is the application which you are securing using Keycloak.

Let’s see how we can create a client in Keycloak:

Go to the ‘Client’ menu in the portal Click on the ‘Create’ button Provide a name to the Client-Id. We’ll call it Rbi-Service in our case.

That’s it!

adding Client

Keep everything to default on next screen and all that you need is to enter a valid redirect URL that will be used by Keycloak on authenticating a user in the application. We will choose to keep it http://localhost:8081/* in the valid redirect URL section.

configure client

Keycloak APIs:

keyclaok in Microservices: (source)

You might be using REST APIs in your current project right now. Don’t worry, Keycloak provides full support for REST APIs. In fact, it also provides an entire admin console, which can be used via REST APIs.

Here’s a list of the possible Keycloak admin REST APIs.

For admin REST APIs, there is a Java client library that makes it easy to use with Java. To use it from your application — like you do for any third party library — just add a dependency of the keycloak-admin-client library in your project. That’s it.

POM.xml

Application.yml

Note: We would be needed `clientId as admin-cli` of all default client-ids provided by keycloak for implementing REST endpoints provided by keycloak for admin,

REST API implementation

There are several steps to create users in a realm using REST endpoints:

Creating User:

Step 1: Create an instance by using the Master Admin’s details through the getInstance() Method

Keycloak kcMaster = Keycloak.getInstance(serverUrl, masterRealm, masterUsername, masterPassword, masterClientId);

Step 2: Set up User data in UserRepresentation

private String userName; private String firstName; private String lastName; private String email; private String password; private String companyName;

The password is mapped to CredentialRepresentation. You have to the force user to change their password on their first login through the code below:

credential.setTemporary(isTempPassword); and user.setRequiredActions(Arrays.asList(ACTION_UPDATE_PASSWORD));

Finally, all you have to do is to call createUser in a given realm:

kcMaster.realm(request.getCompanyName()).users().create(user);

As Keycloak has its own database, this newly-created user information gets stored in the table: user_entity

Congratulations!! You have just created a user in Keyclaok using a REST endpoint.

2. User login for access and refresh tokens

Now comes a major challenge: logging a user into your Application

Keycloak provides several ways to get an access token based on how you have configured your client in Keycloak. Keycloak gives you AccessTokenResponse, which is a JWT-based token and contains an access token, refresh token and relevant information for these properties.

Login Response

You can re-check detail data, which is embedded with access token on jwt.io

action behind the scenes (source)

Keycloak with Spring:

Keycloak understands API interactions with applications and provides adapters for applications willing to communicate with Keycloak. It has already provided adapters for Javascript, NodeJs applications, WildFly/EAP and Spring Boot.

keycloak dependency with Spring-boot (source)

About Security Config

If you’re a backend developer and you are working with Spring, and you have to work on security-related tasks, then you definitely use Spring Security. Well, there’s good news: there’s a Keycloak Spring security adapter, and it’s included in the Spring Boot keycloak starter.

If you have worked with Spring security, then you might know that the SecurityConfig class extends WebSecurityConfigurerAdapter. This provides a convenient base class for creating a WebSecurityConfigurer instance, and it is needed for any application which uses Spring Security. Keycloak provides a wrapper class over WebSecurityConfigurerAdapter, called KeycloakWebSecurityConfigurerAdapter.

Now let’s see how to combine Spring Security and Keycloak together.

Adding Spring Security Starter

First, we need to add the spring-boot-starter-security artifact in our pom.xml to get Spring Security libraries:

security dependency

Creating a SecurityConfig class

Keyclaok with Spring-Boot (source)

Spring Security Config

Let’s have a closer look at the most important methods:

configureGlobal: If you remember Spring Security, roles are prefixed with ROLE_. This can be done in keycloak as well, but this can create confusion for other applications unaware of this convention. By changing the Granted Authority Mapper, we assign a SimpleAuthorityMapper that will make sure no prefix is added.

keycloakConfigResolver: By default, the Keycloak Spring Security Adapter will scan for a file named keycloak.json present on your classpath. Here, we want to provide the Spring Boot properties file support.

configure: This is where we define our security validations. It is very simple to understand that we are securing the path “/features” with role “user”.

Conclusion:

Building Security component in your application is always difficult and specially when it is Microservices based architecture . There are of-course multiple options available for building Security Service but Keycloak takes that responsibility and helps developers to focus on what there Product or Application demands.

As every component in Keycloak is very well tried and tested so there are very less chances of messing anything when it comes to security modules.

Keycloak has certainly shown great potential for Spring developers to deal with security, especially when development is moving towards building a Microservice strategy.

it is really simple (source)

If you’ve enjoyed this post and want to learn more, I’d encourage to check these codebases on GitHub:

Keycloak-admin-api and Keycloak-with-SpringBoot

Thanks!!

NB: Use of above images complies with fair use standards. More information on can be found here.