Add OpenID Connect (OIDC) sign-in to browser applications using the OAuth 2.0 Authorization Code flow with PKCE. Use the framework-independent client directly, or the React components and hooks.
- Choose a package
- Getting started
- How it works
- Multiple APIs and resource indicators
- Security and deployment
- Run the demos
- FAQ
- Migrations
- Contribute
| Package | Use it for | Documentation |
|---|---|---|
@axa-fr/oidc-client |
Browser applications using any JavaScript framework, or no framework | Installation, configuration, and API |
@axa-fr/react-oidc |
React providers, protected components, authentication hooks, and authenticated fetch | React quick start and recipes |
@axa-fr/oidc-client-service-worker |
The worker used by both clients to isolate tokens and attach them to trusted requests | Setup and deployment · Protocol reference |
Most applications install only one of the first two packages. The service worker is included as a dependency; it does not replace the browser client.
Features include automatic token renewal, named configurations for multiple providers or scopes, optional service-worker token isolation, and support for DPoP and Pushed Authorization Requests (PAR) when supported by your authorization server.
Authenticated fetch binds DPoP proofs to the HTTP method and absolute request URI, with the query and fragment omitted from the proof. See the FAQ on DPoP target mismatches.
-
Register a public browser client with your OIDC provider. Enable the Authorization Code flow with PKCE and register your exact callback and post-logout URLs. Do not put a client secret in browser code.
-
Install the package for your application:
# Framework-independent applications npm install @axa-fr/oidc-client # React applications — choose this instead npm install @axa-fr/react-oidc
-
Follow the vanilla JavaScript quick start or the React quick start. Set your provider's
authority,client_id,redirect_uri, andscope. -
Choose whether to use the service worker. Its setup requires serving
OidcServiceWorker.jsand configuringOidcTrustedDomains.js; installing the npm package alone is not sufficient.
Your provider must allow requests from your application origin to the endpoints
the browser calls, including the token endpoint. Request offline_access only
when your provider and client registration support refresh tokens.
The client creates a PKCE challenge, redirects the browser to the provider, and exchanges the returned authorization code for tokens. In service-worker mode, the worker intercepts the token exchange and authenticated API requests:
sequenceDiagram
actor User
participant App as Browser application
participant Worker as OIDC service worker
participant Provider as OIDC provider
participant API as Trusted API
User->>App: Select sign in
App->>Provider: Authorization request with PKCE challenge
Provider->>User: Authenticate and request consent
Provider-->>App: Redirect to callback with authorization code
App->>Worker: Exchange code with PKCE verifier
Worker->>Provider: Token request
Provider-->>Worker: Tokens
Worker-->>App: Token metadata and secured placeholders
App->>Worker: Request to a configured trusted API
Worker->>API: Request with access token
API-->>App: API response
With the default token-hiding settings, the real access and refresh tokens stay in the worker; the application receives placeholders instead. Without the worker, the client manages tokens in browser storage and the authenticated fetch wrapper adds the access token to API requests.
Routine service-worker synchronization checks for script updates at most once per hour per registration within a page. Cold starts and version-mismatch recovery still check for updates. See the worker update FAQ.
Session restoration tolerates missing or malformed saved login parameters in both storage modes and waits for expired tokens to be renewed before reporting success. Await restoration before reading tokens or starting authenticated work. Failed restoration clears page tokens and stops renewal and session monitoring before worker cleanup. See session restoration for retry behavior and cleanup limitations.
The React renewTokens() hook returns null token fields when core
renewal produces no tokens, and authentication state follows current tokens on
renewal/error events. See the React hook guide.
Observe renewal checks through subscribeEvents in the core client or onEvent
in React. The token synchronization events guide
explains their payloads and timing: an _end event can also report session loss
or deferred renewal, and does not guarantee that tokens were refreshed.
RFC 8707 Resource Indicators
let one OIDC session acquire separate access tokens for explicitly configured
APIs. Configure resources with permitted API URL prefixes and, for JWT access
tokens, the provider's audience values. resource selects the resource or
resources included in the initial authorization grant.
// After signing in with the multi-API configuration linked below:
const ordersFetch = oidcClient.fetchForResource('https://orders.example.com', fetch);
const inventoryFetch = oidcClient.fetchForResource('https://inventory.example.com', fetch);
const [orders, inventory] = await Promise.all([
ordersFetch('https://orders.example.com/v1/orders'),
inventoryFetch('https://inventory.example.com/v1/items'),
]);
if (!orders.ok || !inventory.ok) throw new Error('A protected API request failed.');See the complete multi-API configuration and lifecycle example
and React resource hooks.
Resource caches do not overwrite the default or sibling access tokens.
Resource fetch rejects destinations outside its mappings and automatic
redirects; a configured worker additionally enforces its trusted-domain rules.
Use explicit resource selection for resource-managed API origins, including with
fetchWithTokens(). Existing configurations without resources keep their
current fetch behavior.
Without a resource registry, callbacks and local session clearing continue to
honor custom storage without adding native sessionStorage access. Explicit
iframe-only login retains its fulfilled error-result convention; check the
returned value for Error. The new resource-acquisition methods reject on failure.
Default-token renewal keeps its own entry even with a single configured resource. Restoring persisted resource tokens notifies subscribers, while resource clearing also invalidates in-flight cache lookups. Concurrent login calls share one authorization transaction while resource state is cleared.
Providers must honor resource indicators. The client checks configured JWT audiences but cannot inspect opaque-token audiences. Unsupported targets, missing silent-login setup, login/consent requirements, and incompatible workers produce errors rather than a different-resource token fallback. Short-lived resource tokens cap the renewal margin at half their lifetime. Additional authorization requires a fresh ID token for the same user; resource refresh grants may omit ID tokens.
- Service-worker isolation is not an XSS or CSRF prevention mechanism. Malicious code running in the application can still make requests on the user's behalf. Apply a restrictive Content Security Policy and normal input/output protections.
- Use HTTPS in production. Service workers require a secure context; localhost is suitable for development.
- Restrict
OidcTrustedDomains.jsto the provider endpoints and API URLs that should receive tokens. Review these rules whenever you add an API. - Keep
OidcServiceWorker.jsaligned with the installed library version using the copy command andpostinstallinstructions in the package guides. - Decide explicitly whether to permit fallback to browser storage or require the
worker with
service_worker_only: true. Browser storage is accessible to same-origin JavaScript. - Configure your host to serve the application at callback URLs. If you enable silent sign-in, use a separate silent callback URL and account for browser restrictions on third-party cookies.
- Protect APIs on the server: a client-side route guard is not an authorization boundary.
See the FAQ for deployment and security considerations.
Local development now defaults to the OpenIddict .NET fixture.
After installing the .NET 10 SDK and running pnpm install --frozen-lockfile and
pnpm build, run pnpm demo:server, pnpm demo:react, and pnpm demo:native
in separate terminals. Use React at http://localhost:5173/resources and native
at http://localhost:5174/ to test two isolated RFC 8707 API audiences.
Append ?dpop=true&worker=on or ?dpop=true&worker=off to compare DPoP modes.
Use the registered localhost origins, not 127.0.0.1 or [::1].
Switching to browser storage removes the demo's OIDC worker and reloads before
authentication starts. Close other tabs of the same demo when switching modes;
worker registrations are origin-wide and tokens are not migrated between modes.
Changing dpop clears this tab's demo OIDC sessions, resource tokens and proof
keys, and releases the demo worker before obtaining a grant in the selected
proof mode. The Alice provider session is retained.
On React's /multi-auth page, sign in as Alice once, then use Silent Login
with a configuration that enables silent callbacks. It reuses the provider
session and the selected configuration's scopes/resources without navigating
the main page. Select config_with_dpop to use DPoP for that named configuration;
its Selected configuration proof label is independent of the default
configuration's mode banner. Missing provider sessions report login_required.
Production builds retain Duende. Set VITE_OIDC_PROVIDER=duende to use Duende
in development. The fixture's DPoP and session-monitoring adapters are custom
demo-only integrations, not native OpenIddict features or production security.
See the fixture guide for registered origins, callback differences, provider
limitations and the credential-masked browser evidence.
The local-demo Actions workflow checks the built packages' public types, both demo production builds, .NET tests and Chromium end-to-end scenarios.
Try the hosted React demo or vanilla JavaScript demo. These are learning environments, not production security templates.
To run locally, use a Node.js version supported by the root
package.json and its pinned pnpm version. From the repository
root:
corepack enable
pnpm install --frozen-lockfile
pnpm buildStart pnpm demo:server for the Vite demos, then choose one command, also from
the repository root:
| Demo | Command | Guide |
|---|---|---|
| Vanilla JavaScript (Vite) | pnpm demo:native |
Callbacks, session restoration, and token isolation |
| React (Vite) | pnpm demo:react |
Hooks, protected components, API requests, and multiple configurations |
| Next.js (Pages Router) | pnpm --dir examples/nextjs-demo dev |
Browser authentication and custom history integration |
The Vite demo commands require the registered ports: React uses
http://localhost:5173 and native uses http://localhost:5174.
The Next.js demo retains its external provider and uses http://localhost:3001.
When using an external provider, register the actual origin and callback URLs
before testing sign-in; its availability and registrations are outside this
repository's control.
Start with the FAQ for common integration questions, then consult the package guides for configuration and error handling. To report a problem, open an issue with a minimal reproduction, browser and package versions, and sanitized configuration. Never include tokens or credentials.
Read the contribution guide and code of conduct. The workspace contains the client, React bindings, service worker, and demo applications.
Dependency updates must include the affected workspace manifests and
pnpm-lock.yaml. Use the pinned pnpm 12.21.0 version; CI reads it from the root
packageManager field. Keep Vitest and @vitest/coverage-v8 on matching versions.
The publishing workflow pins npm 12.2.2 for trusted publishing.
Vitest 5.1 supports MSW 3. Dependency updates respect pnpm's release-age policy;
MSW 3.0.6 is deferred while it is inside that window.
Run pnpm audit --audit-level low to check all workspace dependencies, including
development and optional dependencies. CI runs the same audit without ignored
advisories. The targeted minimatch override in pnpm-workspace.yaml addresses
GHSA-g3hv-75wg-m249 until typescript-eslint updates its dependency range. A clean
audit covers known published advisories, not every possible security flaw.
The .NET fixture audits direct and transitive NuGet dependencies during restore,
with audit warnings treated as errors. Its Microsoft dependencies stay on the
latest .NET 10 patch line; upgrading Entity Framework Core 11 requires .NET 11.
GitHub Actions installs Node.js before pnpm. The Node setup steps disable
automatic package-manager caching (package-manager-cache: false) so they do
not try to invoke pnpm before it is installed. Workflow actions are pinned to
commit hashes, with release versions in comments; Dependabot checks npm, NuGet,
and GitHub Actions updates.
Before submitting or updating any pull request, all of these checks must pass, including for documentation-only changes. Run them sequentially so the tests use completed build artifacts:
pnpm lint-fix
pnpm lint
pnpm build
pnpm test:ci
pnpm test:e2eThe E2E suite requires the .NET 10 SDK and Playwright Chromium
(pnpm exec playwright install chromium). It starts its own local demo servers;
stop manually started instances first. See the local fixture verification guide.