MicroProfile JWT Authentication with Keycloak and React

Last Updated:  May 15, 2021 | Published: January 10, 2019

For securing your enterprise applications you have several choices that require different configuration setups. Lately, the stateless approach is the de-facto standard for securing your microservice-based landscape. With the choice, your applications don't store session data.  The client mostly sends a JWT token with each request and thus the applications access metadata like groups and email. To standardize the authorization workflow, OAuth 2.0 was created. On top of this specification, OpenID Connect offers a layer for clients to identify application users based on the authentication performed by an authorization server. With Keycloak and MicroProfile JWT Auth, we can achieve such authentication and authorization mechanisms with almost no additional code.

Keycloak is an identity-provider which is open source, based on WildFly and developed by RedHat and is used quite often. In enterprise projects, you can even connect Keycloak to an existing LDAP or Active Directory for enterprise user management.

In this blog post, I'll show you a simple setup for a JWT authentication within a Java EE 8 application with the latest MicroProfile JWT 1.1 spec running on Payara. For the identity and access management, I am using Keycloak (4.8.2.Final) and a React (16.7) based frontend to model a straightforward system architecture. In the end, you will be able to authenticate with your Keycloak user, get visual information about the metadata in the JWT and access a secured JAX-RS resource to obtain a secret message.

Start a Keycloak instance with Docker

The following chapter will explain how to set up the Keycloak server from scratch. You can either follow this step-by-step guide or build an already preconfigured Keycloak server from the Dockerfile I'm providing in my GitHub repository (if you use the preconfigured version, you just have to get the public RSA key from Keycloak admin console and create a sample user).

To start the Keycloak server locally I am using the official jboss/keycloak docker image with the version 4.8.2.Final. For accessing the Keycloak internals you have to pass an admin account and password during the container startup and map the port 8080 to a local port like:

In this example, I am using my port 8282 so that there won't be a conflict with Payara later on. After the container successfully started, you can now visit the admin panel in your browser at http://localhost:8282 and use the user and password you passed to the docker container to authenticate.

Setting up Keycloak for JWT

First, we have to set up a new realm, which is a logical container for managing users, credentials, roles, and groups which are then isolated from other realms. At default, only the Master realm exists and to add a new one, you have to create a new in the admin panel at the top left (while hovering over the drop-down indicator):

 

addANewRealmInsideKeycloak

 

On the following page add the name MicroProfile and make sure the realm is enabled. Next, go to the Keys tab within the Realm Settings and copy the public key of the rsa-generated key to an editor or clipboard. We will need this key later on for verifying the JWT signature within the Java EE backend.

To provide groups for the user, you have to first create some groups. Go to Manage -> Groups -> and click on New to add a group. Enter a group name e.g. ADMIN or USER and press Save. That's all for adding a group.

As we won't connect an Active Directory or LDAP, we have to set up at least one user manual. Go to Users (left-side menu) and click Add User. Enter a username and hit save. To add a password, go to the Credentials tab within the user and enter a password of your choice:

 

managePasswordInsideKeycloak

Within the user settings, you can switch to the tab Groups and select an available group and hit Join to add this user to the group.

configureGroupsInsideKeycloak

Add the React frontend as a client inside Keylcoak

Our frontend will, later on, manage the authentication with Keycloak. Therefore we have to make sure that Keycloak is aware of this application. Therefore Keycloak offers the concept of a client, which is an entity that can request Keycloak to authenticate a user. A new client can be added in the Clients section (left-side menu) in the admin panel within our realm. Click on Add Client and enter the client id react-webapp. Next, select openid-connect as the protocol and http://localhost:3000 as the root URL:

 

addTheReactClientInsideKeycloak

As Keycloak per default won't add the users' group information to the JWT, we have to configure this. Within the client settings for react-webapp, go to the tab Mappers and create a new one. Select Group Membership as Mapper Type, enter group as Name and groups as Token Claim Name. Make sure to disable the Full group path switch. Otherwise we get a slash in front of the group name (e.g. /USER):

 

keycloakProtocolMapper

To configure the frontend for the Keycloak authentication we need the Keycloak OIDC JSON. We can obtain this at the tab Installation within our client.

The JSON should look like the following:

That's all for the Keycloak configuration. All your configured groups, roles and clients can be exported within the Export menu section.

Setting up the frontend with React

Within this chapter I'll show you the required steps to integrate Keycloak within React to produce the following application:

 

reactFrontendDisplayingJWTInformation

To bootstrap a simple React app I've used the create-react-app CLI. In addition, I've added semantic-ui-react, axios, and the keycloak-js dependency:

I'm using just the generated App component and perform the authentication with Keycloak when the component did mount:

The required keycloak.json can be placed within the public folder and is the Keycloak OIDC JSON you get from the Keycloak admin interface (one of the last steps within setting up Keycloak). The init function will check if the user is already authenticated and if not, will redirect to the Keycloak authentication page:

 

keycloakLoginPage

 

The user can now enter this username and his credentials to authenticate. After he got successfully authenticated, Keycloak will redirect the user to the React app. The authentication status is then stored within the state of the App component.

In addition, I am decoding the public part of the JWT as this is just a Base64 encoded string.

Therefore I am using the following function:

For accessing the secured JAX-RS endpoint, the JWT token has to be attached to the HTTP Authorization header.

With axios as HTTP client this is pretty straightforward:

You can find the whole JSX/HTML of the App component on GitHub.

Setting up the backend with MicroProfile JWT Auth

The backend application has to verify the integrity of the passed JWT token. Next, it maps the JWT claims to a Java object and the available groups to Java EE roles if the JWT is valid. The MicroProfile JWT spec manages all of this. The specification defines a set of JWT claims which have to be present and describes how perform the authentication. You can get further information in the official spec document.
To bootstrap the Java EE 8 and Microprofile 2.0.1 application, I'm using my own Maven archetype which produces the following pom.xml:

As the frontend request comes from a different origin, I've added a simple CORS JAX-RS filter:

The JAX-RS application configuration is pretty straightforward:

The @LoginConfig(authMethod = "MP-JWT") is required to enable the MP-JWT authentication mechanism within the application server. In addition, I'm defining the available roles with the declarative annotation, which could also be part of the web.xml file.

Access the JWT inside a JAX-RS resource

Within the JAX-RS resource I'm providing a simple endpoint which is accessible for users within the USER group:

The JsonWebToken interface is part of the MicroProfile JWT spec and holds all the JWT claims and is compatible with the JSR 375 caller Principal.
For the JWT verification, you have to configure at least the name of the issuer and the public key of the RSA signature. The specification defines several configurations. I am using the microprofile-config.properties file within src/main/resources/META-INF:

And store the public key in the configured location like:

With this configuration, we can now deploy the Java EE application to Payara. If you are using my Maven archetype you can deploy the application and start Payara as a Docker container with the buildAndRun batch or bash script.

You can find the whole codebase on GitHub and try it out locally.

Have fun securing your applications with MicroProfile JWT Auth and Keycloak,

Phil

  • Thank you.
    I have read a lots of articles, blogs.
    Everyone trying to show how much they know about different libraries, technologies. However, they are not able to provide functional and working code.
    Th

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >