Keycloak Integration With Gatsby/React
The backend API expects a Keycloak access token and the UI must allow the user to authenticate herself and then send the access token with every request. If this sounds like your JIRA ticket, then stick around.
Prerequisites
A Keycloak server instance. I am using the Docker image (v11.0.2) running on http://localhost:8080
. For a walkthrough on setting up Keycloak, check out my article on How to configure Keycloak for a Web App.
The Gatsby App
Let’s start by creating a simple Gatsby application. The easiest way would be to clone the Gatsby starter git repo https://github.com/gatsbyjs/gatsby-starter-hello-world.
To handle the communication with the Keycloak server we will use the @react-keycloak/web
, which in turn uses keycloak-js
, the official javascript adapter for Keycloak. Let's add the two dependencies:
npm install @react-keycloak/web keycloak-js
Now let’s create a keycloak.js
file, which will hold the keycloak-js
instance. To configure it you need the URL, realm, and client id of your Keycloak server.
@react-keycloak/web
has a ReactKeycloakProvider
, which will initialize the keycloak-js
instance. We will use the gatsby-browser.js
, which offers a way to wrap the root element of our app.
The keycloak-js
instance is passed as the authClient
property. The onLoad: “login-required”
option will transfer the user to the Keycloak login page once the app is loaded in the browser. And finally, the LoadingComponent
is rendered while the page is… well… loading.
Once authenticated the user will land on the index.js
page where we will output the authentication status and a logout button. The status, access tokens, and logout method are provided by the keycloak-js
instance (see Keycloak JavaScript Adapter), which we will get using the useKeycloak
hook.
Now, let’s test the app. To start the dev mode run npm run develop
. The app should be available under http://localhost:8000
. If everything goes smoothly, once you open it in the browser you should be redirected to the Keycloak login page. After a successful login, you should see the index.js
page with our message and the logout button.
The next thing we need is to use the access token we received from Keycloak in our requests to the server. The access token is provided by the keycloak-js
instance using keycloak.token
and you should usually attach it to the request in the Authorization
header. Here is an example with axios
:
Where to go from here
The keycloak-js
instance configuration is currently hard-coded, but it could also be loaded from a JSON file. When building the web app into a Docker image, for example, you could create the JSON file on-the-fly when spinning up containers. Using environmental variables as parameters, you can make the keycloak-js
instance easily configurable.
You can find the source code to this article on Github under https://github.com/mihaylovin/gatsby-keycloak.
Cheers!