Skip to main content

Open Source User Management, SSO, and Secure Pages for ReactJS

· 4 min read
Jeff Patzer
Phase Two

In this article we'll be using Keycloak to quickly augment an application with user management and single sign on (SSO) using the open source Identity and Access Management System (IAM) Keycloak for Authentication and Authorization. We will demonstrate the integration by securing a page for logged-in users. This quickly provides a jump-off point to more complex integrations.

info

If you just want to skip to the code, visit the Phase Two ReactJS example.

Setting up a Keycloak Instance​

Instructions
tip

If you already have a Keycloak instance, skip to the next section.

You can run Keycloak on your machine with Docker, or use a hosted Phase Two cluster. Both come with Phase Two's Keycloak extensions.

Run Keycloak locally​

The Phase Two examples repo includes a local Phase Two Keycloak that is already set up for the examples: a p2examples realm with a client for each example and a demo user. You need Docker with the Compose plugin.

git clone https://github.com/p2-inc/examples.git
cd examples
docker compose -f keycloak/docker-compose.yml up -d --wait
WhatValue
Issuer URLhttp://localhost:8080/auth/realms/p2examples
Admin consolelocalhost:8080/auth/admin, admin / admin
Demo userdemo / demo

The client and the user from the next two sections already exist in this realm, so you can skip both. The local Keycloak README lists the client of each example. docker compose -f keycloak/docker-compose.yml down stops Keycloak, and the next up starts again from a fresh realm.

Use a hosted Phase Two cluster​

  1. Sign up on the Phase Two Dashboard with an email address, a GitHub account or a Google account.
  2. Create a Starter cluster, which is free for 30 days, and add a realm to it.
  3. Click Open Console to open the realm in the Keycloak admin console.

The app connects to Keycloak through the realm's issuer URL, https://<your-keycloak-host>/auth/realms/<your-realm>. In the admin console, Realm settings > General > Endpoints > OpenID Endpoint Configuration shows it as issuer.

Keep the admin console open: the next sections create the app's client and a user there.

Setting up an OIDC Client​

Instructions

The app needs an OpenID Connect client in Keycloak. The app runs in the browser, where it can't keep a secret, so it gets a public client and logs users in with the authorization code flow and PKCE. Keycloak's docs describe all the client settings.

  1. Open the Keycloak admin console and select your realm.

  2. Click Clients in the menu.

  3. Click Create client.

  4. Leave Client type set to OpenID Connect.

  5. Enter a Client ID. The app sends this ID in its OpenID Connect requests.

  6. Supply a Name for the client.

  7. Click Next.

    Keycloak OIDC Create Client General Settings

  8. Under Capability config:

    • Leave Client authentication off.
    • Leave Standard flow checked and Direct access grants unchecked. The app logs users in through Keycloak's login page, so it never needs their password.
    • Turn Require PKCE on, and leave PKCE Method set to S256.
  9. Click Next.

    Keycloak OIDC Create Client Capability Config

  10. Under Login settings, enter the app's URLs. For an app running on http://localhost:3000:

    Valid redirect URIs (where Keycloak may send users back after they log in)

    http://localhost:3000/*

    Valid post logout redirect URIs (where Keycloak may send users back after they log out; + means the valid redirect URIs)

    +

    Web origins (the origins allowed to call Keycloak from the browser, for example to get tokens; + means the origins of the valid redirect URIs)

    +
    URI and Origin Details

    Use the port of the app you run: most examples run on port 3000, and the Angular examples on 4200. For an app deployed somewhere, use its URL instead of localhost.

  11. Click Save.

    Keycloak OIDC Create Client Login Settings

OIDC Config​

The app needs two values from Keycloak:

  • Issuer URL: the realm's URL, such as http://localhost:8080/auth/realms/p2examples for the local Keycloak, or https://<your-keycloak-host>/auth/realms/<your-realm>. Realm settings > General > Endpoints > OpenID Endpoint Configuration shows it as issuer.
  • Client ID: the ID you entered when you created the client.

Adding a Non-Admin User​

Instructions
tip

It is bad practice to use your admin user to sign in to an application.

The local Keycloak from the examples repo already has a non-admin user, demo / demo. On any other Keycloak, add one:

  1. Open the Keycloak admin console and select your realm.
  2. Click Users in the menu.
  3. Click Add user.
  4. Fill out the Username, Email, First name and Last name. Click Create.
  5. Open the Credentials tab and click Set password. Enter a password for the user. For this tutorial, you can turn Temporary off.
  6. Click Save, then confirm with Save password.

Setting up a ReactJS Project​

info

We will use the Phase Two ReactJS example code here, but the logic could easily be applied to any existing application.

  1. Clone the Phase Two example repo, if you haven't already.

  2. Open the ReactJS folder within /frameworks/reactjs/oidc-client-ts. You need Node.js 24 and pnpm.

  3. Point the app at your Keycloak. The app reads two environment variables, VITE_OIDC_ISSUER_URI and VITE_OIDC_CLIENT_ID. .env holds the values of the hosted Phase Two demo realm, and .env.local overrides them. For the local Keycloak, copy .env.local.sample to .env.local:

    cp .env.local.sample .env.local

    It holds the issuer URL of the local Keycloak and the client it already has for the React examples, reactjs-example:

    VITE_OIDC_ISSUER_URI=http://localhost:8080/auth/realms/p2examples
    VITE_OIDC_CLIENT_ID=reactjs-example

    For another Keycloak, copy the file the same way and replace both values with the Issuer URL and the Client ID from the OIDC Config section. The client ID is the one you entered when you created the client, so it may not be reactjs-example.

  4. Run pnpm install and then pnpm dev. This example leverages react-oidc-context (which uses oidc-client-ts) to provide hook and HOC support.

  5. Open the src/main.tsx file. It builds the OIDC config from the environment variables:

    import { StrictMode } from "react";
    import { createRoot } from "react-dom/client";
    import { AuthProvider, type AuthProviderProps } from "react-oidc-context";
    import App from "./App.tsx";
    import "./index.css";

    const oidcConfig: AuthProviderProps = {
    authority: import.meta.env.VITE_OIDC_ISSUER_URI,
    client_id: import.meta.env.VITE_OIDC_CLIENT_ID,
    redirect_uri: `${window.location.origin}/`,
    post_logout_redirect_uri: `${window.location.origin}/`,
    scope: "openid profile email",
    onSigninCallback: () => {
    window.history.replaceState({}, document.title, window.location.pathname);
    },
    };

    createRoot(document.getElementById("root")!).render(
    <StrictMode>
    <AuthProvider {...oidcConfig}>
    <App />
    </AuthProvider>
    </StrictMode>,
    );

    Keycloak sends users back to the app's origin after they log in and after they log out, which the client's http://localhost:3000/* redirect URI and + post logout redirect URI allow. onSigninCallback removes the authorization response from the URL once the login completes. The config is then provided to the AuthProvider, which wraps the whole app.

    At this point our entire application will be able to access all information and methods needed to perform authentication. View src/Auth.tsx for exactly how the code is authenticating your user. It reads the authentication state with the useAuth() hook, and the sections rendering the "Log in" and "Log out" buttons are conditional areas based on that state. Log in calls auth.signinRedirect(), and Log out calls auth.signoutRedirect().

    The logic using the hook to conditionally determine the Authenticated state, can be used to secure routes, components, and more.

  6. Open localhost:3000. You will see the Phase Two example landing page. Your current status should be "Not authenticated." Click Log in. This will redirect you to your login page.

    info

    Use the non-admin user created in the previous section to sign in. On the local Keycloak, that is demo / demo.

  7. Sign in with the credentials of the non-admin user. You will then be redirected to the application. The Phase Two example landing page now loads your "Authenticated" state, displaying your user's name and email, and the decoded access and ID tokens. The app keeps the tokens in session storage and refreshes them before they expire.

  8. Click Log out. The app ends your Keycloak session too, and Keycloak sends you back to the landing page. When you click Log in again, Keycloak asks for your credentials.

Learning more​

Phase Two's enhanced Keycloak provides many ways to quickly control and tweak the log in and user management experience. Our blog has many use cases from customizing login pages, setting up magic links (passwordless sign in), and Organization workflows.