How to Use Keycloak with React

Keycloak is an open-source identity and access management solution that provides features like Single Sign-On (SSO) and OAuth2 authorization. In this guide, we will explain how to integrate Keycloak with a React application.

Prerequisites

Before getting started, make sure you have the following:

Install Keycloak JavaScript Adapter

To use Keycloak with React, we need to install the Keycloak JavaScript adapter. Open your terminal and navigate to your React project directory. Run the following command to install the adapter:

npm install keycloak-js

Create a Keycloak Configuration

In your React project, create a new file called keycloak.js. This file will contain the Keycloak configuration settings. Add the following code to the keycloak.js file:

import Keycloak from 'keycloak-js';

const keycloakConfig = {
  url: 'https://your-keycloak-server/auth',
  realm: 'your-realm',
  clientId: 'your-client-id',
};

const keycloak = new Keycloak(keycloakConfig);

export default keycloak;

Make sure to replace https://your-keycloak-server/auth, your-realm, and your-client-id with the appropriate values for your Keycloak setup.

Initialize Keycloak in your React App

In your React app's entry file (e.g., index.js), import the keycloak object from the keycloak.js file and initialize it before rendering the app. Add the following code to your entry file:

import React from 'react';
import ReactDOM from 'react-dom';
import keycloak from './keycloak';

keycloak.init({ onLoad: 'login-required' }).then((authenticated) => {
  if (authenticated) {
    ReactDOM.render(<App />, document.getElementById('root'));
  }
});

Secure Routes with Keycloak

To secure specific routes in your React app, you can create a higher-order component (HOC) that wraps the protected components. Create a new file called SecureRoute.js and add the following code:

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import keycloak from './keycloak';

const SecureRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      keycloak.authenticated ? (
        <Component {...props} />
      ) : (
        <Redirect to="/login" />
      )
    }
  />
);

export default SecureRoute;

This SecureRoute component checks if the user is authenticated using keycloak.authenticated. If authenticated, it renders the protected component; otherwise, it redirects to the login page.

Use Secure Routes in your App

Now, you can use the SecureRoute component to secure specific routes in your app. For example:

import React from 'react';
import { BrowserRouter as Router, Switch } from 'react-router-dom';
import SecureRoute from './SecureRoute';
import HomePage from './HomePage';
import DashboardPage from './DashboardPage';

const App = () => (
  <Router>
    <Switch>
      <SecureRoute exact path="/" component={HomePage} />
      <SecureRoute path="/dashboard" component={DashboardPage} />
    </Switch>
  </Router>
);

export default App;

In this example, both the homepage (/) and the dashboard page (/dashboard) are secured routes that can only be accessed by authenticated users.

By following these steps, you can integrate Keycloak with your React application and secure specific routes. Keycloak provides a powerful and secure solution for managing user authentication and authorization in your React projects.


#keycloak#react#javascript