Skip to content

React application with Keycloak PKCE integration for authentication/route guarding with minimal code using the react-oidc-context library.

Notifications You must be signed in to change notification settings

r-ant-2468/keycloak-frontend-react-simple

Repository files navigation

Keycloak Frontend React Simple

This repository gives an example of a simple React application with standardised Keycloak PKCE integration for authentication with minimal code.

This is an example only, focusing on integration. Therefore, styling and additional functionality are kept simple.

Running Application

Requirements:

Note: A working example of a backend REST API service, which includes a fully configured Keycloak instance as a devservice, can be found here: keycloak-backend-quarkus.

  • Node.js (>= 20.19.0)
  • A running Keycloak instance with a client configured with:
    • Protocol: openid-connect
    • Access Type: public
    • Valid Redirect URIs: http://localhost:5173/*
    • Web Origins: http://localhost:5173
    • Valid Post Logout Redirect URIs: http://localhost:5173/*

Running application:

Install dependencies

npm install

Configure Environment Variables Create a .env file in the root directory:

VITE_KEYCLOAK_URL=https://your-keycloak-domain/
VITE_KEYCLOAK_REALM=your-realm-name
VITE_KEYCLOAK_CLIENT=your-client-id

Start Development Server

npm run dev

Project notes

  • The app is wrapped within an AuthProvider context given by the package react-oidc-context - in the main.tsx file.
  • The contained App component references routes using the package react-router-dom.
  • There are two routed pages:
    • Path / Landing page with a link to the Keycloak login page. If authenticated, redirects to /home using the component
    • Path /home Home page a guarded route, showing user information from Keycloak.
  • The home route is contained within a simple guard component which wraps each route within a withAuthenticationRequired higher order component (detailed in the react-oidc-context package). To ensure authentication is required.
  • Authentication information (ex. connected user info) and methods (login/logout) are contained within a custom hook and referenced in multiple components.

Full Tech Stack

AI Usage

No part of this repository may be used to train machine learning models or artificial intelligence without express written permission.

About

React application with Keycloak PKCE integration for authentication/route guarding with minimal code using the react-oidc-context library.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages