Open Source User Management, SSO, and Secure Pages for ReactJS
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.
If you just want to skip to the code, visit the Phase Two ReactJS example.
Setting up a Keycloak Instance
Instructions
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
| What | Value |
|---|---|
| Issuer URL | http://localhost:8080/auth/realms/p2examples |
| Admin console | localhost:8080/auth/admin, admin / admin |
| Demo user | demo / 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
- Sign up on the Phase Two Dashboard with an email address, a GitHub account or a Google account.
- Create a Starter cluster, which is free for 30 days, and add a realm to it.
- 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.
-
Open the Keycloak admin console and select your realm.
-
Click Clients in the menu.
-
Click Create client.
-
Leave Client type set to OpenID Connect.
-
Enter a Client ID. The app sends this ID in its OpenID Connect requests.
-
Supply a Name for the client.
-
Click Next.

-
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.
-
Click Next.

-
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. -
Click Save.

OIDC Config
The app needs two values from Keycloak:
- Issuer URL: the realm's URL, such as
http://localhost:8080/auth/realms/p2examplesfor the local Keycloak, orhttps://<your-keycloak-host>/auth/realms/<your-realm>. Realm settings > General > Endpoints > OpenID Endpoint Configuration shows it asissuer. - Client ID: the ID you entered when you created the client.
Adding a Non-Admin User
Instructions
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:
- Open the Keycloak admin console and select your realm.
- Click Users in the menu.
- Click Add user.
- Fill out the Username, Email, First name and Last name. Click Create.
- Open the Credentials tab and click Set password. Enter a password for the user. For this tutorial, you can turn Temporary off.
- Click Save, then confirm with Save password.
Setting up a ReactJS Project
We will use the Phase Two ReactJS example code here, but the logic could easily be applied to any existing application.
-
Clone the Phase Two example repo, if you haven't already.
-
Open the ReactJS folder within
/frameworks/reactjs/oidc-client-ts. You need Node.js 24 and pnpm. -
Point the app at your Keycloak. The app reads two environment variables,
VITE_OIDC_ISSUER_URIandVITE_OIDC_CLIENT_ID..envholds the values of the hosted Phase Two demo realm, and.env.localoverrides them. For the local Keycloak, copy.env.local.sampleto.env.local:cp .env.local.sample .env.localIt 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/p2examplesVITE_OIDC_CLIENT_ID=reactjs-exampleFor 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. -
Run
pnpm installand thenpnpm dev. This example leverages react-oidc-context (which uses oidc-client-ts) to provide hook and HOC support. -
Open the
src/main.tsxfile. 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.onSigninCallbackremoves the authorization response from the URL once the login completes. The config is then provided to theAuthProvider, 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.tsxfor exactly how the code is authenticating your user. It reads the authentication state with theuseAuth()hook, and the sections rendering the "Log in" and "Log out" buttons are conditional areas based on that state. Log in callsauth.signinRedirect(), and Log out callsauth.signoutRedirect().The logic using the hook to conditionally determine the Authenticated state, can be used to secure routes, components, and more.
-
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.
infoUse the non-admin user created in the previous section to sign in. On the local Keycloak, that is
demo/demo. -
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.
-
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.