Skip to content

Repository files navigation

React OIDC Integration Example

🔐 Modern React + OIDC Authentication

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

ReactViteOIDC


📖 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:

constoidcConfig={client_id: "your-client-id",authority: "https://your-oidc-provider/authority-url",// e.g., Keycloak: http://localhost:8080/realms/MyRealmredirect_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:
SettingValue
Client IDtest-react-web
Client Protocolopenid-connect
Access Typepublic
Standard FlowEnabled
Valid Redirect URIshttp://localhost:5173/*
Web Originshttp://localhost:5173
Admin URLhttp://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:

constoidcConfig={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:

constoidcConfig={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:

constoidcConfig={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";functionProtectedPage(){return(<OidcSecure><YourComponent/></OidcSecure>);}

Accessing User Information

import{useOidcUser}from"@axa-fr/react-oidc";functionUserProfile(){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";functionTokenInfo(){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.jsimport{useOidcAccessToken}from"@axa-fr/react-oidc";exportfunctionuseAxiosInterceptors(){const{ accessToken }=useOidcAccessToken();useEffect(()=>{constrequestInterceptor=axios.interceptors.request.use((config)=>{if(accessToken){config.headers.Authorization=`Bearer ${accessToken}`;}returnconfig;});return()=>axios.interceptors.request.eject(requestInterceptor);},[accessToken]);}

Usage in App.jsx:

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

Making API calls:

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

importaxiosfrom"axios";asyncfunctionfetchProtectedData(){// Token is automatically added by the interceptorconstresponse=awaitaxios.get("http://localhost:8080/api/protected");returnresponse.data;}

📦 Tech Stack

Core Dependencies

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

Dev Dependencies

PackagePurpose
viteBuild tool and dev server
@vitejs/plugin-reactReact support for Vite
eslintCode linting
babel-plugin-react-compilerReact 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

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages