Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

emronr/react-oidc-example

Repository files navigation

React OIDC Integration Example

πŸ” Modern React + OIDC Authentication

A production-ready React application with OpenID Connect (OIDC) authentication integration

React Vite OIDC


πŸ“– About

This project demonstrates a complete implementation of OIDC authentication in a modern React application using OpenID Connect protocol. Works with any OIDC-compliant provider including Keycloak, Auth0, Okta, Azure AD, and more. Built with Vite for optimal performance and developer experience.

✨ Key Features

  • πŸ” OIDC Integration - Full OpenID Connect authentication flow with any provider
  • 🌐 Multi-Provider Support - Works with Keycloak, Auth0, Okta, Azure AD, and more
  • πŸ”„ Token Management - Automatic token refresh and silent renewal
  • πŸ›‘οΈ Protected Routes - Route guards with OidcSecure wrapper
  • πŸ“‘ HTTP Interceptors - Axios interceptors for automatic token injection
  • ⚑ Vite Build Tool - Lightning-fast HMR and optimized builds
  • πŸš€ React 19 - Latest React with compiler optimizations
  • 🎯 React Router v7 - Modern routing with data APIs

πŸ“š Documentation

Medium Article

For a complete guide and detailed explanation:

πŸ“ Connecting OIDC in React Apps: The Practical Guide with Keycloak


πŸš€ Quick Start

Prerequisites

  • Node.js 18.x or higher
  • npm or yarn package manager
  • OIDC Provider - Any OpenID Connect compliant provider:
    • Keycloak (used in this example)
    • Auth0
    • Okta
    • Azure AD / Entra ID
    • Google Identity
    • Or any other OIDC provider

Installation Steps

1. Clone the repository

git clone https://github.com/emronr/react-oidc-example.git
cd react-oidc-example

2. Install dependencies

npm install

3. Configure OIDC Provider

Edit src/configs/AuthConfig.js with your OIDC provider settings:

const oidcConfig = {
 client_id: "your-client-id",
 authority: "https://your-oidc-provider/authority-url", // e.g., Keycloak: http://localhost:8080/realms/MyRealm
 redirect_uri: window.location.origin + "/authentication/callback",
 silent_redirect_uri:
 window.location.origin + "/authentication/silent-callback",
 scope: "openid profile email offline_access",
};

4. Start development server

npm run dev

The application will be available at http://localhost:5173


πŸ—οΈ Project Structure

react-oidc-example/
β”œβ”€β”€ src/
β”‚ β”œβ”€β”€ configs/
β”‚ β”‚ └── AuthConfig.js # OIDC configuration
β”‚ β”œβ”€β”€ hooks/
β”‚ β”‚ └── useAxiosInterceptors.js # Token injection hook
β”‚ β”œβ”€β”€ pages/
β”‚ β”‚ β”œβ”€β”€ AuthTest.jsx # Authentication status demo
β”‚ β”‚ β”œβ”€β”€ BackendRequest.jsx # Protected API call example
β”‚ β”‚ └── Counter.jsx # Simple counter page
β”‚ β”œβ”€β”€ routes/
β”‚ β”‚ └── RouteList.jsx # Application routes
β”‚ β”œβ”€β”€ App.jsx # Main app component
β”‚ β”œβ”€β”€ main.jsx # Application entry point
β”‚ └── index.css # Global styles
β”œβ”€β”€ public/ # Static assets
β”œβ”€β”€ index.html # HTML template
β”œβ”€β”€ vite.config.js # Vite configuration
β”œβ”€β”€ eslint.config.js # ESLint configuration
└── package.json # Project dependencies

βš™οΈ Configuration

OIDC Provider Setup

This example uses Keycloak as the OIDC provider, but you can use any OIDC-compliant provider. Below is the Keycloak setup guide:

Keycloak Configuration

1. Create a Realm

  • Login to Keycloak Admin Console
  • Create a new realm (e.g., MyRealm)

2. Create a Client

  • Go to Clients β†’ Create
  • Configure the following:
Setting Value
Client ID test-react-web
Client Protocol openid-connect
Access Type public
Standard Flow Enabled
Valid Redirect URIs http://localhost:5173/*
Web Origins http://localhost:5173
Admin URL http://localhost:5173

3. Configure Scopes Ensure the following scopes are available:

  • openid
  • profile
  • email
  • offline_access (for refresh tokens)

Application Configuration

Update src/configs/AuthConfig.js with your OIDC provider details:

For Keycloak:

const oidcConfig = {
 client_id: "your-client-id",
 authority: "http://your-keycloak-server/realms/your-realm",
 redirect_uri: window.location.origin + "/authentication/callback",
 silent_redirect_uri:
 window.location.origin + "/authentication/silent-callback",
 scope: "openid profile email offline_access",
};

For Auth0:

const oidcConfig = {
 client_id: "your-auth0-client-id",
 authority: "https://your-domain.auth0.com",
 redirect_uri: window.location.origin + "/authentication/callback",
 silent_redirect_uri:
 window.location.origin + "/authentication/silent-callback",
 scope: "openid profile email",
};

For Azure AD:

const oidcConfig = {
 client_id: "your-azure-client-id",
 authority: "https://login.microsoftonline.com/your-tenant-id/v2.0",
 redirect_uri: window.location.origin + "/authentication/callback",
 silent_redirect_uri:
 window.location.origin + "/authentication/silent-callback",
 scope: "openid profile email",
};

πŸ’» Usage Examples

Protecting Routes

Use OidcSecure to protect components:

import { OidcSecure } from "@axa-fr/react-oidc";
function ProtectedPage() {
 return (
 <OidcSecure>
 <YourComponent />
 </OidcSecure>
 );
}

Accessing User Information

import { useOidcUser } from "@axa-fr/react-oidc";
function UserProfile() {
 const { oidcUser } = useOidcUser();
 return (
 <div>
 <h1>Welcome, {oidcUser.name}</h1>
 <p>Email: {oidcUser.email}</p>
 </div>
 );
}

Accessing Tokens

import { useOidc } from "@axa-fr/react-oidc";
function TokenInfo() {
 const { accessToken, refreshToken } = useOidc();
 console.log("Access Token:", accessToken);
 console.log("Refresh Token:", refreshToken);
}

Making Authenticated API Calls

The app uses the useAxiosInterceptors hook in App.jsx to automatically inject tokens into all Axios requests:

How it works:

// src/hooks/useAxiosInterceptors.js
import { useOidcAccessToken } from "@axa-fr/react-oidc";
export function useAxiosInterceptors() {
 const { accessToken } = useOidcAccessToken();
 useEffect(() => {
 const requestInterceptor = axios.interceptors.request.use((config) => {
 if (accessToken) {
 config.headers.Authorization = `Bearer ${accessToken}`;
 }
 return config;
 });
 return () => axios.interceptors.request.eject(requestInterceptor);
 }, [accessToken]);
}

Usage in App.jsx:

import { useAxiosInterceptors } from "./hooks/useAxiosInterceptors";
function App() {
 useAxiosInterceptors(); // This enables automatic token injection
 // ...
}

Making API calls:

Once the hook is active, all Axios requests will automatically include the Bearer token:

import axios from "axios";
async function fetchProtectedData() {
 // Token is automatically added by the interceptor
 const response = await axios.get("http://localhost:8080/api/protected");
 return response.data;
}

πŸ“¦ Tech Stack

Core Dependencies

Package Version Purpose
@axa-fr/react-oidc ^7.26.3 OIDC/OAuth2 client library
react ^19.2.0 UI framework
react-dom ^19.2.0 React DOM renderer
react-router-dom ^7.13.0 Client-side routing
axios ^1.13.5 HTTP client

Dev Dependencies

Package Purpose
vite Build tool and dev server
@vitejs/plugin-react React support for Vite
eslint Code linting
babel-plugin-react-compiler React compiler optimization

πŸ› οΈ Available Scripts

# Start development server
npm run dev
# Build for production
npm run build
# Preview production build
npm run preview
# Run ESLint
npm run lint

πŸ”’ Security Considerations

  • βœ… Tokens are stored securely by the OIDC library
  • βœ… Automatic token refresh before expiration
  • βœ… Silent token renewal for seamless UX
  • βœ… Protected routes require valid authentication
  • βœ… CORS properly configured for your OIDC provider
  • βœ… PKCE (Proof Key for Code Exchange) support

πŸ› Troubleshooting

Common Issues

Issue: Redirect loop

  • Check that redirect URIs in your OIDC provider match exactly
  • Verify Web Origins/Allowed Origins are configured in your provider

Issue: Token not attached to requests

  • Ensure useAxiosInterceptors() is called in App.jsx
  • Verify Axios instance is properly configured

Issue: CORS errors

  • Add your app URL to Allowed Origins in your OIDC provider settings

Issue: Authority URL not found

  • Verify your authority URL is correct and accessible
  • Check that your OIDC provider's discovery endpoint is available (.well-known/openid-configuration)

πŸ“ License

This project is licensed under the MIT License.


🀝 Contributing

Contributions are welcome! Feel free to:

  • πŸ› Report bugs
  • πŸ’‘ Suggest new features
  • πŸ”§ Submit pull requests

Please ensure all PRs include appropriate tests and documentation.


πŸ‘€ Author

Your Name


Made with ❀️ using React and OIDC

Β© 2026 - Present

About

React OIDC authentication example using Keycloak and @axa-fr/react-oidc. Demonstrates login, logout, token refresh, and session handling in a real-world setup.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

Contributors

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /