This page looks best with JavaScript enabled

Securing React Apps with Keycloak: A Comprehensive Guide

 ·  ☕ 3 min read  ·  ✍️ Dinesh Arora


While there are a variety of authentication services available, including Firebase Authentication and Auth0, there may be situations in your project where you require greater flexibility and control over your user management and authorization with advanced features.

In such cases, Keycloak is an ideal choice as it offers a wide range of features out of the box. Keycloak includes built-in support for OpenID Connect and SAML 2.0, as well as integrations with popular social networks like Google, GitHub, Facebook, and Twitter.

Let’s take a look at how to create a login page using React and keycloak.
Note We will not go over how to install keycloak. You can view the installation of keycloak here

You can install the Keycloak JavaScript adapter for React using npm. In your project directory, run the following command:

1
npm install @react-keycloak/web keycloak-js

You need to set up a Keycloak instance in your React application. You can do this by creating a Keycloak configuration file with the following code:

1
2
3
4
5
6
7
8
9
import Keycloak from "keycloak-js";

const keycloak = new Keycloak({
  url: "https://your-keycloak-server/auth",
  realm: "your-realm",
  clientId: "your-client-id",
});

export default keycloak;

Replace the url, realm, and clientId values with your Keycloak server URL, realm name, and client ID.


Wrap your React application with the KeycloakProvider component to provide the Keycloak context to your app. You can do this by adding the following code to your index.js file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import React from "react";
import ReactDOM from "react-dom";
import { KeycloakProvider } from "@react-keycloak/web";
import keycloak from "./keycloak";

ReactDOM.render(
  <KeycloakProvider keycloak={keycloak}>
    <App />
  </KeycloakProvider>,
  document.getElementById("root")
);

Replace App with the name of your main component.


Create a new component for the login page. This component should contain a form with two input fields for the username and password, and a submit button to submit the form. You can use the following code as a starting point:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import React, { useState } from "react";
import { useKeycloak } from "@react-keycloak/web";

function LoginPage() {
  const { keycloak } = useKeycloak();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      await keycloak.login({
        username,
        password,
      });
    } catch (error) {
      console.error("Failed to log in", error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Username"
        value={username}
        onChange={(event) => setUsername(event.target.value)}
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(event) => setPassword(event.target.value)}
      />
      <button type="submit">Log in</button>
    </form>
  );
}

export default LoginPage;


You can use the login page component in your main component or any other component in your app. You can also add a link to the login page in your app navigation. Here’s an example of how to use the login page component in your main component:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import React from 'react';
import { useKeycloak } from '@react-keycloak/web';
import LoginPage from './LoginPage';

function App() {
  const { keycloak, initialized } = useKeycloak();

  if (!initialized) {
    return <div>Loading...</div>;
  }

  if (!keycloak.authenticated) {
    return <LoginPage />;
  }
  return (
    <div>)

That’s it! With these steps, you should be able to create a login page using React and Keycloak.

Ciao

Share on
Support the author with

Dinesh Arora
WRITTEN BY
Dinesh Arora
Developer