### Install and Run Next.js Demo Source: https://github.com/axafrance/oidc-client/blob/main/examples/nextjs-demo/README.md Clone the repository, navigate to the Next.js demo directory, install dependencies, and start the development server. ```sh git clone https://github.com/AxaGuilDEv/react-oidc.git cd react-oidc/packages/nextjs-demo npm install npm run dev ``` -------------------------------- ### Run React Vite Demo Source: https://github.com/axafrance/oidc-client/blob/main/README.md Instructions to install dependencies and start the React Vite demo application. ```sh # react vite demo cd examples/react-oidc-demo pnpm install pnpm start # then navigate to http://localhost:4200 ``` -------------------------------- ### Run OIDC Client Demo Source: https://github.com/axafrance/oidc-client/blob/main/README.md Instructions to install dependencies and start the OIDC client demo application. ```sh # oidc client demo cd examples/oidc-client-demo pnpm install pnpm start # then navigate to http://localhost:5174 ``` -------------------------------- ### Run oidc-client Demo Source: https://github.com/axafrance/oidc-client/blob/main/CONTRIBUTING.md Install dependencies and start the oidc-client demo application. Navigate to http://localhost:5174 to view it. ```sh cd examples/oidc-client-demo pnpm install pnpm start ``` -------------------------------- ### Run React NextJS Demo Source: https://github.com/axafrance/oidc-client/blob/main/README.md Instructions to install dependencies and start the React NextJS demo application. ```sh # react NextJS demo cd examples/nextjs-demo pnpm install pnpm run dev # then navigate to http://localhost:3001 ``` -------------------------------- ### Run the Demo Application Source: https://github.com/axafrance/oidc-client/blob/main/examples/react-oidc-demo/README.md Clone the repository, navigate to the react package directory, install dependencies, and start the development server to run the demo application. ```sh git clone https://github.com/AxaGuilDEv/react-oidc.git cd react-oidc/packages/react npm install npm start # then navigate to http://localhost:4200 ``` -------------------------------- ### Run React NextJS Demo Source: https://github.com/axafrance/oidc-client/blob/main/CONTRIBUTING.md Install dependencies and start the NextJS demo application. Navigate to http://localhost:3001 to view it. ```sh cd examples/nextjs-demo pnpm install pnpm run dev ``` -------------------------------- ### Service Worker Post-install Script Example Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Example of a postinstall script in package.json to update the Service Worker files upon npm installation. ```sh "scripts": { ... "postinstall": "node ./node_modules/@axa-fr/oidc-client/bin/copy-service-worker-files.mjs public" }, ``` -------------------------------- ### Clone and Run OIDC Client Demo Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Steps to clone the repository, navigate to the demo directory, install dependencies, and start the demo application. ```sh git clone https://github.com/AxaFrance/oidc-client.git cd oidc-client # oidc client demo cd /examples/oidc-client-demo pnpm install pnpm start # then navigate to http://localhost:5174 ``` -------------------------------- ### Run React OIDC Demo Source: https://github.com/axafrance/oidc-client/blob/main/packages/react-oidc/README.md Steps to clone the repository, install dependencies, and start the React OIDC demo application. ```sh git clone https://github.com/AxaFrance/oidc-client.git cd oidc-client pnpm install cd /examples/react-oidc-demo pnpm install pnpm start # then navigate to http://localhost:4200 ``` -------------------------------- ### Run React Vite Demo Source: https://github.com/axafrance/oidc-client/blob/main/CONTRIBUTING.md Install dependencies and start the React Vite demo application. Navigate to http://localhost:4200 to view it. ```sh cd examples/react-oidc-demo pnpm install pnpm start ``` -------------------------------- ### Clone and Install Project Dependencies Source: https://github.com/axafrance/oidc-client/blob/main/CONTRIBUTING.md Clone the repository and install the necessary pnpm packages to set up the development environment. ```sh git clone https://github.com/AxaFrance/oidc-client.git cd oidc-client pnpm install ``` -------------------------------- ### Install @axa-fr/react-oidc Source: https://github.com/axafrance/oidc-client/blob/main/examples/react-oidc-demo/README.md Install the library using npm. This command also generates necessary service worker and trusted domains configuration files if a 'public' folder exists. ```sh npm install @axa-fr/react-oidc --save ``` -------------------------------- ### Install @axa-fr/oidc-client and Copy Service Worker Files Source: https://github.com/axafrance/oidc-client/blob/main/README.md Install the core OIDC client library using npm. After installation, run the provided script to copy the necessary Service Worker files (`OidcServiceWorker.js` and `OidcTrustedDomains.js`) to your public directory. Ensure `OidcServiceWorker.js` is kept up-to-date with library versions. ```sh npm install @axa-fr/oidc-client --save # To install or update OidcServiceWorker.js file, you can run node ./node_modules/@axa-fr/oidc-client/bin/copy-service-worker-files.mjs public # If you have a "public" folder, the 2 files will be created : # ./public/OidcServiceWorker.js <-- will be updated at each "npm install" # ./public/OidcTrustedDomains.js <-- won't be updated if already exist ``` -------------------------------- ### Install @axa-fr/react-oidc and Copy Service Worker Files Source: https://github.com/axafrance/oidc-client/blob/main/README.md Install the React-specific OIDC client package using npm. Similar to the core library, execute the provided script to copy the `OidcServiceWorker.js` and `OidcTrustedDomains.js` files to your public directory. ```sh npm install @axa-fr/react-oidc --save # To install or update OidcServiceWorker.js file, you can run node ./node_modules/@axa-fr/react-oidc/bin/copy-service-worker-files.mjs public # If you have a "public" folder, the 2 files will be created : # ./public/OidcServiceWorker.js <-- will be updated at each "npm install" ``` -------------------------------- ### Install OIDC Client Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Install the @axa-fr/oidc-client package using npm. This command also updates the OidcServiceWorker.js file if you have a public folder. ```sh npm install @axa-fr/oidc-client --save # To install or update OidcServiceWorker.js file, you can run node ./node_modules/@axa-fr/oidc-client/bin/copy-service-worker-files.mjs public # If you have a "public" folder, the 2 files will be created : # ./public/OidcServiceWorker.js <-- will be updated at each "npm install" ``` -------------------------------- ### Basic React OIDC Provider Setup Source: https://github.com/axafrance/oidc-client/blob/main/examples/react-oidc-demo/README.md Configure the OIDC provider with essential settings and custom components for different authentication states. This setup uses a hybrid mode for service workers. ```javascript import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import { OidcProvider } from '@axa-fr/react-oidc'; import Header from './Layout/Header'; import Routes from './Router'; // This configuration use hybrid mode // ServiceWorker are used if available (more secure) else tokens are given to the client // You need to give inside your code the "access_token" when using fetch const configuration = { client_id: 'interactive.public.short', redirect_uri: 'http://localhost:4200/authentication/callback', silent_redirect_uri: 'http://localhost:4200/authentication/silent-callback', scope: 'openid profile email api offline_access', authority: 'https://demo.identityserver.io', service_worker_relative_url: '/OidcServiceWorker.js', service_worker_only: false, }; const Loading = () =>

Loading

; const AuthenticatingError = () =>

Authenticating error

; const Authenticating = () =>

Authenticating

; const SessionLost = () =>

Session Lost

; const ServiceWorkerNotSupported = () =>

Not supported

; const CallBackSuccess = () =>

Success

; //const [isSessionLost, setIsSessionLost] = useState(false); //const onSessionLost = () // setIsSessionLost(true); //} const App = () => ( {/* isSessionLost && */}
); render(, document.getElementById('root')); ``` -------------------------------- ### React Application Startup with OIDCProvider Source: https://github.com/axafrance/oidc-client/blob/main/packages/react-oidc/README.md This snippet shows the basic setup for a React application using the OidcProvider. It configures the OIDC client with essential details like client ID, redirect URIs, and authority, and integrates it with React Router. ```javascript import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import { OidcProvider } from '@axa-fr/react-oidc'; import Header from './Layout/Header'; import Routes from './Router'; // This configuration use hybrid mode // ServiceWorker are used if available (more secure) else tokens are given to the client // You need to give inside your code the "access_token" when using fetch const configuration = { client_id: 'interactive.public.short', redirect_uri: window.location.origin + '/authentication/callback', silent_redirect_uri: window.location.origin + '/authentication/silent-callback', scope: 'openid profile email api offline_access', // offline_access scope allow your client to retrieve the refresh_token authority: 'https://demo.duendesoftware.com', service_worker_relative_url: '/OidcServiceWorker.js', // just comment that line to disable service worker mode service_worker_only: false, demonstrating_proof_of_possession: false, }; const App = () => (
); render(, document.getElementById('root')); ``` -------------------------------- ### React OIDC Provider Setup Source: https://github.com/axafrance/oidc-client/blob/main/packages/react-oidc/README.md Demonstrates how to set up the OidcProvider in a React application with various configuration options and custom components for loading, authentication states, and errors. This configuration uses a hybrid mode for service workers. ```javascript import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import { OidcProvider } from '@axa-fr/react-oidc'; import Header from './Layout/Header'; import Routes from './Router'; // This configuration use hybrid mode // ServiceWorker are used if available (more secure) else tokens are given to the client // You need to give inside your code the "access_token" when using fetch const configuration = { client_id: 'interactive.public.short', redirect_uri: 'http://localhost:4200/authentication/callback', silent_redirect_uri: 'http://localhost:4200/authentication/silent-callback', scope: 'openid profile email api offline_access', authority: 'https://demo.identityserver.io', service_worker_relative_url: '/OidcServiceWorker.js', service_worker_only: false, }; const Loading = () =>

Loading

; const AuthenticatingError = () =>

Authenticating error

; const Authenticating = () =>

Authenticating

; const SessionLost = () =>

Session Lost

; const ServiceWorkerNotSupported = () =>

Not supported

; const CallBackSuccess = () =>

Success

; //const [isSessionLost, setIsSessionLost] = useState(false); //const onSessionLost = ()=>{ // setIsSessionLost(true); //} const App = () => ( {/* isSessionLost && */}
); render(, document.getElementById('root')); ``` -------------------------------- ### Get User Information with Hook Source: https://github.com/axafrance/oidc-client/blob/main/examples/react-oidc-demo/README.md Fetches user information using the `useOidcUser` hook. It handles different loading states, including loading, unauthenticated, and loading errors, before displaying the user data. ```javascript import { useOidcUser, UserStatus } from '@axa-fr/react-oidc'; const DisplayUserInfo = () => { const { oidcUser, oidcUserLoadingState } = useOidcUser(); switch (oidcUserLoadingState) { case UserStatus.Loading: return

User Information are loading

; case UserStatus.Unauthenticated: return

you are not authenticated

; case UserStatus.LoadingError: return

Fail to load user information

; default: return (
User information

{JSON.stringify(oidcUser)}

); } }; ``` -------------------------------- ### get Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md A static method to retrieve an existing OidcClient instance by its name, or creates a new one if it doesn't exist. ```APIDOC ## static get(name?: string): OidcClient ### Description Retrieves an existing OidcClient instance with the specified name, or creates a new instance if it does not exist. ### Parameters - **name** (string) - Optional - The name of the OidcClient instance to retrieve. ### Returns - **OidcClient** - The existing OidcClient instance or a new instance with the specified name. ``` -------------------------------- ### Getting Access Token with useOidcAccessToken Hook Source: https://github.com/axafrance/oidc-client/blob/main/packages/react-oidc/README.md Demonstrates how to retrieve the access token and its payload using the `useOidcAccessToken` hook. It also includes a warning about XSRF protection and token accessibility. ```javascript import { useOidcAccessToken } from '@axa-fr/react-oidc'; const DisplayAccessToken = () => { const { accessToken, accessTokenPayload } = useOidcAccessToken(); if (!accessToken) { return

you are not authentified

; } return (
Access Token

Please consider to configure the ServiceWorker in order to protect your application from XSRF attacks. "access_token" and "refresh_token" will never be accessible from your client side javascript.

{

{JSON.stringify(accessToken)}

} {accessTokenPayload != null && (

{JSON.stringify(accessTokenPayload)}

)}
); }; ``` -------------------------------- ### OidcTrustedDomains.js Configuration Examples Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Defines trusted domains for OIDC server and API access, with options for showing access tokens, enabling DPoP, and managing multi-tab logins. ```javascript // OidcTrustedDomains.js // Add bellow trusted domains, access tokens will automatically injected to be send to // trusted domain can also be a path like https://www.myapi.com/users, // then all subroute like https://www.myapi.com/useers/1 will be authorized to send access_token to. // Domains used by OIDC server must be also declared here const trustedDomains = { default: { oidcDomains: ['https://demo.duendesoftware.com'], accessTokenDomains: ['https://www.myapi.com/users'], }, }; // Service worker will continue to give access token to the JavaScript client // Ideal to hide refresh token from client JavaScript, but to retrieve access_token for some // scenarios which require it. For example, to send it via websocket connection. trustedDomains.config_show_access_token = { oidcDomains: ['https://demo.duendesoftware.com'], accessTokenDomains: ['https://www.myapi.com/users'], showAccessToken: false, // convertAllRequestsToCorsExceptNavigate: false, // default value is false // setAccessTokenToNavigateRequests: true, // default value is true // bypassAllNonOidcRequests: false, // default value is false; when true, requests outside OIDC and accessTokenDomains are handled by the browser }; // DPoP (Demonstrating Proof of Possession) will be activated for the following domains trustedDomains.config_with_dpop = { domains: ['https://demo.duendesoftware.com'], demonstratingProofOfPossession: true, demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent: true, // default value is false, inject DPOP token only when DPOP header is present // Optional, more details bellow /*demonstratingProofOfPossessionConfiguration: { importKeyAlgorithm: { name: 'ECDSA', namedCurve: 'P-256', hash: {name: 'ES256'} }, signAlgorithm: {name: 'ECDSA', hash: {name: 'SHA-256'}}, generateKeyAlgorithm: { name: 'ECDSA', namedCurve: 'P-256' }, digestAlgorithm: { name: 'SHA-256' }, jwtHeaderAlgorithm : 'ES256' }*/ }; // Setting allowMultiTabLogin to true will enable storing login-specific parameters (state, nonce, code verifier) // separately for each tab. This will prevent errors when logins are initiated from multiple tabs. // IMPORTANT: When allowMultiTabLogin is true, you MUST use the OIDC fetch provided by // oidcClient.fetchWithTokens(fetch) for API requests. The service worker embeds a tab-specific // token placeholder in the Authorization header, which it then replaces with the real access token. // Using a plain fetch or axios without the OIDC fetch wrapper will result in requests being sent // without an Authorization header (401 errors), because the service worker cannot determine which // tab's token to inject without the placeholder. // Example with axios: configure it to use the OIDC fetch as its adapter or use the OIDC fetch directly. trustedDomains.config_multi_tab_login = { domains: ['https://demo.duendesoftware.com'], allowMultiTabLogin: true, }; ``` -------------------------------- ### Automate Service Worker File Updates with npm Postinstall Script Source: https://github.com/axafrance/oidc-client/blob/main/README.md To ensure the `OidcServiceWorker.js` file is always up-to-date with the library version, add a `postinstall` script to your `package.json`. This script automatically runs the service worker file copy command after each `npm install`. ```json { "scripts": { ... "postinstall": "node ./node_modules/@axa-fr/oidc-client/bin/copy-service-worker-files.mjs public" }, } ``` -------------------------------- ### Update Service Worker Files Source: https://github.com/axafrance/oidc-client/blob/main/packages/react-oidc/README.md Configure a postinstall script in package.json to automatically update the OidcServiceWorker.js file at each npm install. ```json { "scripts": { ... "postinstall": "node ./node_modules/@axa-fr/react-oidc/bin/copy-service-worker-files.mjs public" } } ``` -------------------------------- ### Fetch User Info with useOidcFetch Hook Source: https://github.com/axafrance/oidc-client/blob/main/examples/react-oidc-demo/README.md Use the `useOidcFetch` hook to get a wrapped fetch function that automatically injects the access token. This is suitable for scenarios where you are not using a service worker. ```javascript import React, { useEffect, useState } from 'react'; import { useOidcFetch, OidcSecure } from '@axa-fr/react-oidc'; const DisplayUserInfo = ({ fetch }) => { const [oidcUser, setOidcUser] = useState(null); const [isLoading, setLoading] = useState(true); useEffect(() => { const fetchUserInfoAsync = async () => { const res = await fetch('https://demo.duendesoftware.com/connect/userinfo'); if (res.status != 200) { return null; } return res.json(); }; let isMounted = true; fetchUserInfoAsync().then(userInfo => { if (isMounted) { setLoading(false); setOidcUser(userInfo); } }); return () => { isMounted = false; }; }, []); if (isLoading) { return <>Loading; } return (
User information
{oidcUser != null &&

{JSON.stringify(oidcUser)}

}
); }; export const FetchUserHook = () => { const { fetch } = useOidcFetch(); return ( ); }; ``` -------------------------------- ### React Application Startup with OIDC Provider Source: https://github.com/axafrance/oidc-client/blob/main/examples/react-oidc-demo/README.md Sets up the main React application, including the OIDC provider, router, and essential components. Ensure the configuration object is correctly defined with your OIDC server details and redirect URIs. This configuration uses a hybrid mode for service workers. ```javascript import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import { OidcProvider } from '@axa-fr/react-oidc'; import Header from './Layout/Header'; import Routes from './Router'; // This configuration use hybrid mode // ServiceWorker are used if available (more secure) else tokens are given to the client // You need to give inside your code the "access_token" when using fetch const configuration = { client_id: 'interactive.public.short', redirect_uri: window.location.origin + '/authentication/callback', silent_redirect_uri: window.location.origin + '/authentication/silent-callback', scope: 'openid profile email api offline_access', // offline_access scope allow your client to retrieve the refresh_token authority: 'https://demo.duendesoftware.com', service_worker_relative_url: '/OidcServiceWorker.js', service_worker_only: false, }; const App = () => (
); render(, document.getElementById('root')); ``` -------------------------------- ### OIDC Client Initialization and Callback Handling Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Initializes the OIDC client with configuration and handles the login callback, redirecting to the home page upon successful authentication. ```javascript import { OidcClient } from '@axa-fr/oidc-client'; export const configuration = { client_id: 'interactive.public.short', redirect_uri: window.location.origin + '/#/authentication/callback', silent_redirect_uri: window.location.origin + '/#/authentication/silent-callback', scope: 'openid profile email api offline_access', authority: 'https://demo.duendesoftware.com', service_worker_relative_url: '/OidcServiceWorker.js', // just comment that line to disable service worker mode service_worker_only: false, demonstrating_proof_of_possession: false, }; const href = window.location.href; const oidcClient = OidcClient.getOrCreate()(configuration); // Use the fetch bellow to inject access_token and DPOP tokens automatically const oidcFetch = oidcClient.fetchWithTokens(fetch); // You can inject you own fetch (default Fetch Interface) function and location object (respecting IOidcLocation interface) // import {OidcLocation} from '@axa-fr/oidc-client' // const oidcClient = OidcClient.getOrCreate(() => fetch, new OidcLocation())(configuration); console.log(href); oidcClient.tryKeepExistingSessionAsync().then(() => { if (href.includes(configuration.redirect_uri)) { oidcClient.loginCallbackAsync().then(() => { window.location.href = '/'; }); } }); ``` -------------------------------- ### OIDC Client Demo Initialization Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Initializes the OIDC client and sets up the UI based on authentication status. Displays login or logout buttons and token information. ```javascript import { OidcClient } from "@axa-fr/oidc-client"; const configuration = { client_id: "client_id", scope: "scope", authority: "https://localhost:5000", redirect_uri: "https://localhost:5000/authentication/login-callback", post_logout_redirect_uri: "https://localhost:5000/authentication/logout-callback", }; const oidcClient = new OidcClient(configuration); oidcClient.loadTokens().then(() => { let tokens = oidcClient.tokens; if (tokens) { // @ts-ignore window.logout = () => oidcClient.logoutAsync(); document.body.innerHTML = `

@axa-fr/oidc-client demo

Authenticated

${JSON.stringify(tokens, null, '\t')}
`; } else { // @ts-ignore window.login = () => oidcClient.loginAsync('/'); document.body.innerHTML = `

@axa-fr/oidc-client demo

`; } }); ``` -------------------------------- ### Get ID Token with Hook Source: https://github.com/axafrance/oidc-client/blob/main/examples/react-oidc-demo/README.md Retrieves the ID token and its payload using the `useOidcIdToken` hook. Displays the token information if the user is authenticated. ```javascript import { useOidcIdToken } from '@axa-fr/react-oidc'; const DisplayIdToken = () => { const { idToken, idTokenPayload } = useOidcIdToken(); if (!idToken) { return

you are not authentified

; } return (
ID Token
{

{JSON.stringify(idToken)}

} {idTokenPayload != null &&

{JSON.stringify(idTokenPayload)}

}
); }; ``` -------------------------------- ### Get Access Token with Hook Source: https://github.com/axafrance/oidc-client/blob/main/examples/react-oidc-demo/README.md Uses the `useOidcAccessToken` hook to retrieve the access token and its payload. It includes a warning about XSRF protection and ServiceWorker configuration. ```javascript import { useOidcAccessToken } from '@axa-fr/react-oidc'; const DisplayAccessToken = () => { const { accessToken, accessTokenPayload } = useOidcAccessToken(); if (!accessToken) { return

you are not authentified

; } return (
Access Token

Please consider to configure the ServiceWorker in order to protect your application from XSRF attacks. "access_token" and "refresh_token" will never be accessible from your client side javascript.

{

{JSON.stringify(accessToken)}

} {accessTokenPayload != null && (

{JSON.stringify(accessTokenPayload)}

)}
); }; ``` -------------------------------- ### Demonstrating Proof of Possession Configuration Interface Source: https://github.com/axafrance/oidc-client/blob/main/packages/react-oidc/README.md Defines the structure for configuring the Demonstrating Proof of Possession feature, specifying algorithms for key generation, signing, and hashing. ```typescript interface DemonstratingProofOfPossessionConfiguration { generateKeyAlgorithm: RsaHashedKeyGenParams | EcKeyGenParams, digestAlgorithm: AlgorithmIdentifier, importKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, signAlgorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, jwtHeaderAlgorithm: string }; ``` -------------------------------- ### Default Demonstrating Proof of Possession Configuration Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Provides the default configuration values for the Demonstrating Proof of Possession feature, specifically setting the import key algorithm to ECDSA. ```typescript // default value of demonstrating_proof_of_possession_configuration const defaultDemonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration ={ importKeyAlgorithm: { name: 'ECDSA', ``` -------------------------------- ### Demonstrating Proof of Possession Configuration Interface Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Defines the interface for configuring the Demonstrating Proof of Possession feature, specifying algorithms for key generation, digest, import, signing, and JWT header. ```typescript interface DemonstratingProofOfPossessionConfiguration { generateKeyAlgorithm: RsaHashedKeyGenParams | EcKeyGenParams, digestAlgorithm: AlgorithmIdentifier, importKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, signAlgorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, jwtHeaderAlgorithm: string }; ``` -------------------------------- ### Default Demonstrating Proof of Possession Configuration Source: https://github.com/axafrance/oidc-client/blob/main/packages/react-oidc/README.md Provides the default configuration values for the Demonstrating Proof of Possession feature, using ECDSA with P-256 curve and SHA-256. ```typescript const defaultDemonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration ={ importKeyAlgorithm: { name: 'ECDSA', namedCurve: 'P-256', hash: {name: 'ES256'} }, signAlgorithm: {name: 'ECDSA', hash: {name: 'SHA-256'}}, generateKeyAlgorithm: { name: 'ECDSA', namedCurve: 'P-256' }, digestAlgorithm: { name: 'SHA-256' }, jwtHeaderAlgorithm : 'ES256' }; ``` -------------------------------- ### generateDemonstrationOfProofOfPossessionAsync Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Generates a Demonstration of Proof of Possession (DPOP) token. ```APIDOC ## generateDemonstrationOfProofOfPossessionAsync ### Description Generates a Demonstration of Proof of Possession (DPOP) token. ### Method Asynchronous function call ### Parameters * **accessToken** (string) - Required - The access token to use. * **url** (string) - Required - The URL to use for the DPOP request. * **method** (string) - Required - The HTTP method to use for the DPOP request. * **extras** (StringMap) - Optional - Additional parameters to send to the OIDC server during the DPOP request. Defaults to an empty object. ### Returns A promise resolved with the proof of possession string, or rejected with an error. ``` -------------------------------- ### Use OIDC Fetch Wrapper with Axios Configuration (React) Source: https://github.com/axafrance/oidc-client/blob/main/FAQ.md If using Axios, configure it to use the OIDC fetch wrapper or directly use the `fetch` function provided by `useOidcFetch` for API calls when `allowMultiTabLogin` is true. This ensures proper token handling. ```javascript import { useOidcFetch } from '@axa-fr/react-oidc'; const MyComponent = () => { const { fetch } = useOidcFetch(); const callApi = async () => { // Use the OIDC fetch directly instead of axios when allowMultiTabLogin is true const res = await fetch('https://my-api.example.com/data', { method: 'GET', headers: { 'Content-Type': 'application/json' }, }); return res.json(); }; // ... }; ``` -------------------------------- ### OIDC Client Configuration Options Source: https://github.com/axafrance/oidc-client/blob/main/packages/react-oidc/README.md Configuration object for initializing the OIDC client. Includes settings for session monitoring, token renewal modes, and proof of possession. ```typescript const oidcConfig = { // ... other configurations monitor_session: Boolean, onLogoutFromAnotherTab: Function, onLogoutFromSameTab: Function, token_renew_mode: String, token_automatic_renew_mode: TokenAutomaticRenewMode.AutomaticOnlyWhenFetchExecuted, logout_tokens_to_invalidate: Array, location: ILOidcLocation, demonstrating_proof_of_possession: Boolean, demonstrating_proof_of_possession_configuration: DemonstratingProofOfPossessionConfiguration }; // Example of TokenAutomaticRenewMode usage: // TokenAutomaticRenewMode.AutomaticBeforeTokensExpiration: renew tokens automatically before they expire // TokenAutomaticRenewMode.AutomaticOnlyWhenFetchExecuted: renew tokens automatically only when fetch is executed // It requires you to use fetch given by hook useOidcFetch(fetch) or HOC withOidcFetch(fetch)(Component) ``` -------------------------------- ### Migrate Fetch Wrappers from v3 to v4 Source: https://github.com/axafrance/oidc-client/blob/main/MIGRATION_GUIDE_V3_TO_V4.md Shows how to update fetch wrappers for handling HTTP requests with OIDC authentication. `withFetchRedirectionOn401`, `withFetchSilentAuthenticateAndRetryOn401`, `withFetchRedirectionOn403`, and `withAuthentication` are removed in v4. `withFetchToken` is renamed to `withOidcFetch` and is now part of the main context package. ```javascript // old v3 import { withFetchRedirectionOn401, withFetchSilentAuthenticateAndRetryOn401, withFetchRedirectionOn403, withAuthentication } from '@axa-fr/react-oidc-context-fetch'; // new v4 import { withOidcFetch } from '@axa-fr/react-oidc-context'; // withFetchRedirectionOn401 : removed, you have to implement your own 401 management // withFetchSilentAuthenticateAndRetryOn401 : removed, not necessary in v4 token are in auto refresh mode only // withFetchRedirectionOn403 : removed, you have to implement your own 403 management // withAuthentication : removed // withFetchToken in v3 have been rename to withOidcFetch and set inside '@axa-fr/react-oidc-context' package withOidcFetch() ``` -------------------------------- ### OidcClient Constructor Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Initializes an OidcClient instance with an existing Oidc object. This is the primary way to create a client instance for managing OIDC operations. ```APIDOC ## constructor(oidc: Oidc) ### Description Creates an instance of OidcClient using a provided `Oidc` object. ### Parameters - **oidc** (Oidc) - Required - The instance of the underlying Oidc object to use. ``` -------------------------------- ### OIDC Configuration Options Source: https://github.com/axafrance/oidc-client/blob/main/packages/react-oidc/README.md This snippet outlines the extensive configuration options available for the OidcProvider. It covers components for loading and error states, session management, and detailed OIDC parameters. ```javascript const configuration = { loadingComponent: ReactComponent, // you can inject your own loading component sessionLostComponent: ReactComponent, // you can inject your own session lost component authenticating: ReactComponent, // you can inject your own authenticating component authenticatingErrorComponent: ReactComponent, callbackSuccessComponent: ReactComponent, // you can inject your own call back success component serviceWorkerNotSupportedComponent: ReactComponent, // you can inject your page that explains you require a more modern browser onSessionLost: Function, // If set, "sessionLostComponent" is not displayed, and onSessionLost callback is called instead configuration: { client_id: String.isRequired, // oidc client id redirect_uri: String.isRequired, // oidc redirect url silent_redirect_uri: String, // Optional activate silent-signin that use cookies between OIDC server and client javascript to restore sessions silent_login_uri: String, // Optional, route that triggers the signin silent_login_timeout: Number, // Optional, default is 12000 milliseconds scope: String.isRequired, // oidc scope (you need to set "offline_access") authority: String.isRequired, storage: Storage, // Default sessionStorage, you can set localStorage, but it is not secure login_state_storage: Storage, // Optional. Storage used only for authorization flow state (state, code_verifier, nonce, login params). Defaults to the value of `storage`. Set to sessionStorage when using storage: localStorage to prevent race conditions when multiple tabs start the login flow simultaneously. authority_configuration: { // Optional for providers that do not implement OIDC server auto-discovery via a .wellknown URL authorization_endpoint: String, token_endpoint: String, userinfo_endpoint: String, end_session_endpoint: String, revocation_endpoint: String, check_session_iframe: String, issuer: String, }, refresh_time_before_tokens_expiration_in_second: Number, // default is 120 seconds service_worker_relative_url: String, service_worker_keep_alive_path: String, // default is "/" service_worker_only: Boolean, // default false service_worker_activate: () => boolean, // you can take the control of the service worker default activation which use user agent string service_worker_register: (url: string) => Promise, // Optional, you can take the control of the service worker registration extras: StringMap | undefined, // ex: {'prompt': 'consent', 'access_type': 'offline'} list of key/value that is sent to the OIDC server (more info: https://github.com/openid/AppAuth-JS) token_request_extras: StringMap | undefined, // ex: {'prompt': 'consent', 'access_type': 'offline'} list of key/value that is sent to the OIDC server during token request (more info: https://github.com/openid/AppAuth-JS) withCustomHistory: Function, // Override history modification, return an instance with replaceState(url, stateHistory) implemented (like History.replaceState()) authority_time_cache_wellknowurl_in_second: 60 * 60, // Time to cache in seconds of the openid well-known URL, default is 1 hour authority_timeout_wellknowurl_in_millisecond: 10000, // Timeout in milliseconds of the openid well-known URL, default is 10 seconds, then an error is thrown } ``` -------------------------------- ### Update Fetch Wrappers: v3 vs v5 Source: https://github.com/axafrance/oidc-client/blob/main/MIGRATION_GUIDE_V3_TO_V5.md Understand the changes in fetch redirection and authentication wrappers. Several v3 wrappers are removed in v5, requiring custom implementation for 401/403 error handling. The `withFetchToken` wrapper is renamed to `withOidcFetch` and moved to the main context package. ```javascript // old v3 import { withFetchRedirectionOn401, withFetchSilentAuthenticateAndRetryOn401, withFetchRedirectionOn403, withAuthentication } from '@axa-fr/react-oidc-context-fetch'; // new v5 import { withOidcFetch } from '@axa-fr/react-oidc-context'; // withFetchRedirectionOn401 : removed, you have to implement your own 401 management // withFetchSilentAuthenticateAndRetryOn401 : removed, not necessary in v4 token are in auto refresh mode only // withFetchRedirectionOn403 : removed, you have to implement your own 403 management // withAuthentication : removed // withFetchToken in v3 have been rename to withOidcFetch and set inside '@axa-fr/react-oidc-context' package withOidcFetch() ``` -------------------------------- ### Update OIDC Hooks: v3 vs v5 Source: https://github.com/axafrance/oidc-client/blob/main/MIGRATION_GUIDE_V3_TO_V5.md Compare the import statements and hook usage for OIDC context between v3 and v5. Note that v5 hooks like `useOidc`, `useOidcUser`, `useOidcAccessToken`, and `useOidcIdToken` replace the single `useReactOidc` hook from v3. Login and logout in v5 return Promises. ```javascript // old v3 import { useReactOidc } from '@axa-fr/react-oidc-context'; const { isEnabled, login, logout, oidcUser, events } = useReactOidc(); // new v5 import { useOidc, useOidcAccessToken, useOidcIdToken, useOidcUser, } from '@axa-fr/react-oidc-context'; const { login, logout, isAuthenticated } = useOidc(); // login and logout return a Promise const { oidcUser, oidcUserLoadingState } = useOidcUser(); // Return user_info endpoint data const { accessToken, accessTokenPayload } = useOidcAccessToken(); // Contain access_token metadata acess_token is a JWK const { idToken, idTokenPayload } = useOidcIdToken(); // contain IDToken metadata ``` -------------------------------- ### Use OIDC Fetch Wrapper for API Calls (Vanilla JS) Source: https://github.com/axafrance/oidc-client/blob/main/FAQ.md For vanilla JavaScript applications, use `oidcClient.fetchWithTokens(fetch)` to create a fetch function that correctly injects tokens when `allowMultiTabLogin` is enabled. This ensures requests are authenticated. ```javascript const oidcFetch = oidcClient.fetchWithTokens(fetch); const res = await oidcFetch('https://my-api.example.com/data'); ``` -------------------------------- ### Configure New Properties for Session Monitoring and Caching Source: https://github.com/axafrance/oidc-client/blob/main/MIGRATION_GUIDE_V5_TO_V6.md V6 introduces new configuration options including `authority_time_cache_wellknowurl_in_second` for caching OIDC discovery endpoints, `monitor_session` to enable session monitoring, and callbacks for session events. It also supports manual configuration of `check_session_iframe` for providers without auto-discovery. ```javascript // New properties export const configurationIdentityServer = { ..., authority_time_cache_wellknowurl_in_second: 60* 60, // Time to cache in second of openid wellknowurl, default is 1 hour monitor_session:true, // Add OpenId monitor session, default is true (more information https://openid.net/specs/openid-connect-session-1_0.html) onLogoutFromAnotherTab: Function, // Optional, can be set to override the default behavior, this function is triggered when user with the same subject is logged out from another tab when session_monitor is active onLogoutFromSameTab: Function, // Optional, can be set to override the default behavior, this function is triggered when user is logged out from same tab when session_monitor is active authority_configuration: PropTypes.shape({ // Optional for providers that does not implement OIDC server auto discovery via a .wellknowurl ..., check_session_iframe: PropTypes.string // Optional, route from OIDC server necessary for monitoring session feature }), }; ``` -------------------------------- ### configuration Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Getter for the OIDC configuration currently used by the OidcClient instance. ```APIDOC ## get configuration(): OidcConfiguration ### Description Retrieves the current OIDC configuration used by the OidcClient instance. ### Returns - **OidcConfiguration** - The current OIDC configuration. ``` -------------------------------- ### loginAsync Source: https://github.com/axafrance/oidc-client/blob/main/packages/oidc-client/README.md Initiates the OIDC login flow, allowing for customization of the callback path, additional parameters, and silent login behavior. ```APIDOC ## loginAsync(callbackPath?: string, extras?: StringMap, isSilentSignin?: boolean, scope?: string, silentLoginOnly?: boolean): Promise ### Description Starts the OIDC login process with specified options. ### Parameters - **callbackPath** (string) - Optional - The callback path for authentication. - **extras** (StringMap) - Optional - Additional parameters to send to the OIDC server during the login request. - **isSilentSignin** (boolean) - Optional - Indicates if the login is silent. - **scope** (string) - Optional - The OIDC scope for the login request. - **silentLoginOnly** (boolean) - Optional - Indicates if only silent login is allowed. ### Returns - **Promise** - A promise resolved with the login information, or rejected with an error. ``` -------------------------------- ### Commit Message Conventions for Major Versions Source: https://github.com/axafrance/oidc-client/blob/main/CONTRIBUTING.md Use these commit message formats to publish major versions (x.0.0). Include the word 'BREACKING' in the message. Suffixes like (alpha), (beta), or (release) control the publication stage. ```sh - fix(oidc): my message containing BREACKING word (alpha) => will publish next major as an alpha - fix(oidc): my message containing BREACKING word (beta) => will publish next major as an beta - fix(oidc): my message containing BREACKING word (release) => will publish next major release (with automatic git tag and release) ```