Skip to content

Latest commit

 

History

History
619 lines (493 loc) · 32.7 KB

FAQ.md

File metadata and controls

619 lines (493 loc) · 32.7 KB

Frequently asked questions

Start with the React guide or vanilla JavaScript guide for installation. These answers describe the current source; check the documentation for your installed version when an option is unavailable. Linked issues provide context, not guarantees that every reported problem is resolved.

Contents

How do I test RFC 8707 locally with OpenIddict?

Follow the local fixture guide. The development demos default to OpenIddict, while production builds still use Duende. Both demos expose separate Orders/Inventory API calls, renewal, local clearing, wrong-destination rejection and explicit provider errors. Run pnpm test:server and pnpm test:e2e for the server and browser suites.

Build validation and E2E tests are mandatory before submitting or updating any pull request, including documentation-only changes. Follow the complete, sequential contribution checks.

The fictional Alice sign-in requires no credentials. DPoP and session monitoring use custom loopback-only adapters; they are not native OpenIddict features or a production server. Local OAuth callbacks are fragment-free. Restarting the ephemeral-key server requires fresh authentication. Use exact localhost ports and clear site storage when switching providers. The browser suite captures credential-masked screenshots, not raw tokens or traces.

Local mode rejects 127.0.0.1 and [::1] because only localhost browser origins are registered. Switching from worker=on to worker=off unregisters this demo's OIDC worker and reloads before using browser storage; unrelated workers are left alone. Close other tabs of the same demo before switching, since registrations are origin-wide. 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, so a cached Bearer grant cannot be reused as DPoP or vice versa. The Alice provider cookie remains available for fresh sign-in.

The demo CI also type-checks the built packages. React packaging must copy only worker runtime assets: flattening the worker's nested declaration files can overwrite React's public type entry point and hide all its exported APIs.

Why does CI fail to locate pnpm during Node setup?

If Node setup attempts package-manager caching before pnpm is installed, it can fail with Unable to locate executable file: pnpm. The workflows set package-manager-cache: false on actions/setup-node, then enable Corepack and install the pinned pnpm version with pnpm/action-setup before installing dependencies. This fixes the setup failure; it does not bypass lint, tests, or build checks.

How are dependency vulnerabilities checked?

Install from the repository root with the pinned pnpm 12.21.0 version and pnpm install --frozen-lockfile, then run pnpm audit --audit-level low. CI checks production, development, and optional dependencies without advisory exceptions. The scoped minimatch override fixes GHSA-g3hv-75wg-m249 in the typescript-eslint dependency tree; it must remain until the upstream range is patched. Build, lint, unit, and browser tests also check upgrade compatibility.

The OpenIddict fixture enables NuGet auditing for direct and transitive packages and treats audit warnings as errors. To inspect its reports, run dotnet list examples/openiddict-server/OpenIddictDemo.csproj package --vulnerable --include-transitive and the equivalent command for examples/openiddict-server.tests/OpenIddictDemo.Tests.csproj. Microsoft packages remain on the .NET 10 patch line to match the fixture target. A clean report means no advisories known to the queried registry at that time; it cannot guarantee the absence of undiscovered vulnerabilities.

Why can an Azure demo deployment fail after a successful build?

Azure Static Web Apps can reject a deployment when the app has reached its maximum number of staging environments. An app administrator must remove an unused staging environment before retrying the deployment. Updating npm dependencies does not resolve this Azure quota.

How do I call multiple APIs with different audiences?

Use resource-specific configuration and fetch or the React resource hooks. Register exact resource identifiers and permitted API URL prefixes in resources; use resource to include supported targets in the initial authorization grant. Scopes describe permissions, not audiences. For JWT tokens, configure the provider's audiences separately from the resource URI.

Each resource has its own access-token entry. Shared refresh rotation does not replace sibling/default access tokens, and local resource clearing does not revoke the shared grant. Managed API origins require explicit resource selection; automatic redirects are rejected. Worker mode also requires matching trusted domains and a compatible deployed worker.

Default-token renewal remains separate from explicit resource acquisition, including single-resource grants. Restoring a stored resource token publishes its acquisition event; clearing prevents pending cache lookups from restoring it afterward.

If the provider rejects resource with invalid_target, the client does not strip it or use another token. Additional resources/scopes may require silent authorization; missing callback routes, blocked cookies, login_required, consent_required, and timeouts are explicit errors. Offer a user-driven authorization action instead of an automatic interactive redirect. Providers reusing an identical refresh token across separate authorization transactions must use an initial multi-resource grant for this API. Additional authorization must return a fresh ID token for the same user and nonce. Resource refresh may omit ID tokens, even after a previous ID token has expired. Resource renewal margins are capped at half the access-token lifetime to avoid immediate renewal loops for short-lived API tokens.

Opaque tokens cannot be checked for an audience, and JWTs without configured audience mappings rely on provider correctness. Use only providers known to honor resource indicators; the client does not add introspection or token exchange. After worker memory is lost, restore or reauthenticate the original session rather than attempting to reuse stale token placeholders.

Why are React exports missing after a workspace build?

Build the workspace with pnpm build. React packaging must copy only the worker runtime assets; flattening nested worker declarations into React's distribution can overwrite its public index.d.ts. The React artifact test checks that all named exports survive packaging.

Do I need a service worker?

No. Omit service_worker_relative_url and leave service_worker_only: false (the default) to use browser storage:

const configuration = {
  client_id: 'your-public-client',
  authority: 'https://issuer.example.com',
  redirect_uri: `${window.location.origin}/authentication/callback`,
  scope: 'openid profile',
  service_worker_only: false,
};

Without a worker, token storage defaults to sessionStorage. You can choose localStorage, but both are readable by same-origin JavaScript.

Worker mode keeps access and refresh tokens in worker memory by default. Follow the worker setup guide; installing the package alone does not serve or configure the worker files.

In React, service_worker_only: true makes the provider show its unsupported-worker screen when it receives the worker-unavailable event. This is not a core-client guarantee against browser-storage fallback: the vanilla client can still use browser storage when worker initialization returns no worker. If token isolation is mandatory, do not rely on this flag alone; verify worker availability and prevent authentication from proceeding without it in your integration.

When testing a switch away from worker mode, unregister the application's old OIDC worker in browser developer tools and reload the page. Removing the configuration does not unregister an already installed worker.

Why is my access token a placeholder?

In worker mode, values such as ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER_... are expected when access-token hiding is enabled. The worker holds the real token and replaces the placeholder on matching trusted requests. Refresh tokens are also hidden; the ID token and decoded claims can still be available to application code.

Use useOidcFetch() in React or oidcClient.fetchWithTokens(fetch) in vanilla JavaScript rather than trying to decode or send the placeholder yourself. showAccessToken: true in the matching OidcTrustedDomains.js entry exposes the access token to application JavaScript; use it only if your integration requires that trade-off. It does not expose the refresh token.

Developer tools can show the application request and the worker's outgoing request. Inspect which request actually failed: duplicate-looking entries do not by themselves prove a bug, but a failed token exchange is not something to ignore. See #1703.

Why does my API return 401, especially with multiple tabs?

Check these separately:

  1. Wait for authentication before calling a protected API.
  2. Use the OIDC fetch wrapper and select the correct configuration name.
  3. In worker mode, check that the worker controls the page and that the API URL matches accessTokenDomains for that configuration in OidcTrustedDomains.js. Follow the trusted-domain rules; do not broaden the allowlist to arbitrary destinations.
  4. Check the API's expected issuer, audience, and scopes. Attaching a token does not guarantee that the API will accept it.

With allowMultiTabLogin: true in OidcTrustedDomains.js, the worker uses the tab-specific placeholder in the Authorization header to select the session. A plain fetch or default Axios call without that marker cannot select the tab's token.

In a React component beneath the matching OidcProvider, obtain the wrapper with useOidcFetch imported from @axa-fr/react-oidc:

const { fetch: oidcFetch } = useOidcFetch();

For an initialized vanilla client:

const oidcFetch = oidcClient.fetchWithTokens(fetch);

Then use it after authentication:

const response = await oidcFetch('https://api.example.com/data');
if (!response.ok) {
  throw new Error(`API request failed with status ${response.status}`);
}
const data = await response.json();

React also provides withOidcFetch. For Axios, use an integration that actually routes requests through the OIDC fetch wrapper, or use the wrapper directly; changing libraries alone does not supply the tab marker. Only call trusted URLs with the wrapper: it is not itself a destination allowlist.

Why does my API reject the DPoP target URI?

For a request to https://localhost:5002/v1/usecases?filter=all, the DPoP htu claim is https://localhost:5002/v1/usecases. The resource server must compare it against the absolute request URI, ignoring the query and fragment. If the API is behind a reverse proxy, use the API's trusted proxy configuration to recover the scheme and authority seen by the browser. See RFC 9449, sections 4.2 and 4.3.

Authenticated fetch resolves relative URLs against the document's base URL and uses the URL and effective HTTP method of Request inputs. The query parameters still reach the API.

Why does login fail when two tabs sign in together?

Without a worker, storage: localStorage shares authorization state, the PKCE verifier, and nonce between tabs using the same configuration. Concurrent login flows can overwrite one another and cause state-validation failures.

If you deliberately want shared token storage, merge these options into your configuration to keep authorization-flow state isolated per tab:

const storageOptions = {
  storage: localStorage,
  login_state_storage: sessionStorage,
};

This changes browser-storage behavior, not worker storage. For independent worker-mode logins, configure allowMultiTabLogin: true and use the OIDC fetch wrapper as described above.

Do not disable state or nonce validation to work around a callback failure. For other causes, see the errors guide.

How are tokens renewed?

By default, the client schedules renewal before expiry. Normal renewal uses a refresh token when one is available; otherwise it attempts the configured iframe-based silent-login flow.

flowchart TD
    Due["Tokens need renewal"] --> Refresh{"Refresh token available?"}
    Refresh -->|Yes| Endpoint["Request tokens from the token endpoint"]
    Refresh -->|No| Silent["Attempt configured silent sign-in"]
    Endpoint --> Result{"Renewal succeeds?"}
    Silent --> Result
    Result -->|Yes| Continue["Continue with renewed tokens"]
    Result -->|No| Recovery["Handle the error; interactive sign-in may be needed"]
Loading

Your provider controls whether it issues refresh tokens, their lifetime, and rotation policy. Some providers require offline_access and additional client settings or consent; adding that scope alone is not a guarantee.

Silent login requires separate silent-login/callback routes and a usable provider session. See the silent-login setup. The React provider handles these routes; vanilla applications must implement them.

For renewal only when a protected request needs it, use TokenAutomaticRenewMode.AutomaticOnlyWhenFetchExecuted with the OIDC fetch wrapper or getValidTokenAsync(). See token renewal. This is not a user-inactivity detector. If you need an idle logout, implement activity tracking in your application and enforce appropriate session limits at the provider/server.

Related questions: #1368 and #1070.

What do syncTokensAsync events mean?

syncTokensAsync_begin starts a synchronization run, and syncTokensAsync_end reports its resolved status. An end event can report SESSION_LOST or GIVE_UP; it does not guarantee a token refresh or completed storage updates. Automatic checks also emit these events when the existing tokens are still valid, and internal refresh retries share one lifecycle pair.

syncTokensAsync_error reports an exception escaping synchronization, which is then rethrown. Resolved session-loss results retain their refresh error events and finish with syncTokensAsync_end. In React, a synchronization error calls onSessionLost() when supplied; otherwise, the provider selects its session-loss screen.

See the event payloads, boundaries, and subscription example. Use subscribeEvents or React's onEvent to record selected diagnostic fields; do not log complete payloads or exceptions, which may contain sensitive data.

Why are tokens renewed every few seconds?

Compare your token lifetimes with refresh_time_before_tokens_expiration_in_second. Its default is 120 seconds, with a random reduction of up to 39 seconds when the configured value exceeds 60. A token whose lifetime is near or below the renewal margin can trigger frequent renewal.

The default token_renew_mode, 'access_token_or_id_token_invalid', uses the earlier access-token or ID-token expiry. Check both lifetimes, not just the access token. The other modes are 'access_token_invalid' and 'id_token_invalid'; choose one only if it matches your application's needs.

Adjust the renewal margin or provider-issued lifetimes together. No client-side setting can extend a token's server-defined validity or guarantee timely background execution.

Why does silent sign-in fail in some browsers?

Silent sign-in loads the provider in a hidden iframe with prompt=none. It depends on an existing provider session, cookies being available in that iframe, and the provider allowing the flow and framing.

Browser privacy settings and third-party-cookie restrictions can prevent this. Hosting the application and provider on the same site can help with cookie restrictions, but does not guarantee success. For example, https://app.example.com and https://login.example.com are different origins, even though they are normally same-site.

Check the registered silent_redirect_uri, the iframe's network errors, provider cookie settings, and CSP/frame restrictions. A provider response such as login_required or consent_required may require interactive sign-in. Refresh-token renewal does not use this iframe flow, although refresh tokens can still expire or be revoked.

Explicit iframe-only login retains its existing promise convention: loginAsync(undefined, undefined, false, undefined, true) in the core client or login(undefined, undefined, true) in React resolves failures with an Error value. Inspect the awaited result as well as silent-login events. Disabled silent callbacks resolve undefined. Resource-token acquisition is a separate API and rejects failures. Failed explicit silent login preserves the existing tokens and renewal timer.

Without a resources registry, callbacks and local session clearing honor custom storage without introducing native sessionStorage access. Resource transaction bookkeeping uses native tab-scoped sessionStorage when enabled.

In the local React Multi Auth demo, sign in as Alice first, then select a configuration with silent callbacks and click Silent Login. The request uses that configuration's scopes and resources. Overriding the scopes with only openid profile email while requesting Orders/Inventory causes invalid_scope: those resources require orders.read and inventory.read. Errors are displayed on the page; without an Alice cookie, login_required is expected.

For DPoP, select config_with_dpop or use ?dpop=true&worker=on (or worker=off). The named configuration's Selected configuration proof label shows its effective mode; the top banner describes the default configuration. Use Call both APIs to verify that both results report tokenType: "DPoP". The local adapter is demo-only, not native OpenIddict DPoP support.

Can a session be restored without saved login parameters?

Yes. tryKeepExistingSessionAsync() tolerates missing or malformed saved login parameters with both service-worker and browser token storage. Existing tokens are still required; renewal starts without any saved extras or scope overrides. Login callback state and nonce validation remain required.

Other restoration errors clear page tokens and cached user information and stop renewal/session monitoring before worker cleanup. A later call can retry. Worker cleanup can still reject, leaving page authentication state cleared. See session restoration.

Why do I see service-worker script update requests?

The client explicitly checks for script updates on first initialization and at most once per hour per registration within the current page, including failed checks. Routine token timer ticks reuse that check. A replacement registration is checked immediately, and version-mismatch recovery can force a check. Browsers can also initiate their own update checks, independently of this limit. OidcKeepAliveServiceWorker.json requests are a separate keep-alive mechanism; neither mechanism guarantees that the browser retains worker memory.

Can restoration report success with expired stored tokens?

tryKeepExistingSessionAsync() checks expiry and waits for expired tokens to be renewed before returning true, for both worker and browser storage. This also applies to fetch-triggered renewal mode. It returns false if renewal cannot produce tokens, rather than waiting for the first one-second timer tick after restoration. Await that promise before reading tokens or sending authenticated requests. This does not extend refresh-token lifetimes or restore lost worker secrets; an available refresh token or usable silent sign-in flow is required.

What does React's renewTokens return after session loss?

When the core client returns no tokens, useOidc().renewTokens() resolves with null access-token and ID-token fields instead of throwing a null-property error. Actual exceptions from the core API still reject the promise. Renewal and synchronization events update isAuthenticated from current client tokens, so an error with retained tokens does not force a signed-out state. Use the provider's session-loss screen or events for recovery, and the core renewTokensOrThrowAsync() API when you need strict renewal errors.

Will I stay signed in after sleep or a browser restart?

Not necessarily. Browsers can suspend timers and terminate service workers; worker tokens are held in memory, not durable token storage. Provider session cookies may outlive the worker. If its tokens are lost, signing in again depends on an available sign-in flow; silent sign-in also needs a usable provider session.

flowchart TD
    Session["Authenticated browser application"] --> Pause["Sleep, suspension, or browser restart"]
    Pause --> Resume["Application resumes or starts"]
    Resume --> Restore{"Existing session can be restored?"}
    Restore -->|Yes| Use["Use or renew available tokens"]
    Restore -->|No| SignIn["Sign in again"]
Loading

Network reconnection, token expiry, and cookie restrictions can all affect recovery. Worker keep-alive requests are not a persistence guarantee. With browser storage, localStorage can persist across browser sessions, but that neither extends token validity nor makes tokens inaccessible to JavaScript.

Handle session loss with a clear sign-in action rather than an endless retry loop. React offers sessionLostComponent and onSessionLost; vanilla clients can subscribe to client events. See #1147 for sleep/renewal reports and #1662 for a persistence proposal, not an implemented persistence option.

Does logout sign me out of every application?

Not automatically. These are distinct operations:

  • Local session clearing: clearSessionAsync() removes this client's local session without provider logout or token revocation.
  • Standard logout: logoutAsync() (or React's logout()) attempts configured token revocation when the provider exposes a revocation endpoint, uses its end-session endpoint when available, and clears the local session. Register the intended post-logout URL with the provider.
  • Single logout across applications: propagation depends on the provider, its logout/session protocols, and the other applications. Ending one local session is not proof that every application or API token is now signed out.

Check discovery metadata, provider logout requirements, and failed revocation requests. Do not assume that serving all applications on one domain enables single logout. See #820 for an example of provider-specific logout configuration.

What does session monitoring require?

monitor_session defaults to false. When enabled, it needs the provider's check_session_iframe, a session_state, and configured silent-login routes. It checks for changes to the provider session; it is not a general token-expiry or user-idle timer.

This iframe-based mechanism is also subject to browser cookie/privacy policies and provider support. It cannot guarantee immediate logout detection across applications. Keep API authorization and session-expiry enforcement on the server.

Why is the worker unavailable or outdated?

Check the deployment before changing authentication logic:

  1. Serve OidcServiceWorker.js and OidcTrustedDomains.js from your application's origin as JavaScript, not the SPA HTML fallback.
  2. Confirm that service_worker_relative_url points to the deployed file and that its scope covers the application and callback pages.
  3. Run the package's worker-copy command after upgrades. It replaces OidcServiceWorker.js but preserves an existing OidcTrustedDomains.js; maintain your trusted-domain entries yourself.
  4. In browser developer tools, inspect the active registration and which worker controls the tab. Already-open tabs and cached assets can complicate updates.
  5. Check secure-context support and registration errors. Review the service_worker_only limitation before relying on that flag to prevent browser-storage fallback.

For an application under a subpath, account for the worker URL and allowed scope. service_worker_register allows custom registration, but does not bypass browser scope restrictions. See the deployment guide, #1181 (scope), and #1648 (updates).

Can I use an existing PWA worker or a mobile WebView?

Do not assume either works without integration testing.

A page has one controlling service worker at a time. An existing PWA worker and the OIDC worker need a deliberate registration, scope, and fetch/message-handling design. Custom registration is available, but blindly combining worker scripts can cause conflicts. #914 discusses integration approaches, not a universal supported recipe.

WebView capabilities and restrictions vary by platform and host application. service_worker_activate can change the library's activation decision, but cannot add missing browser APIs. Decide whether browser-storage fallback is acceptable, then test login, API calls, renewal, and logout in your actual environment. See #1389.

Why is window.crypto.subtle unavailable?

The Web Crypto crypto.subtle API and service workers require a secure context. Use HTTPS in production. Browsers generally treat http://localhost as trustworthy for local development; an HTTP LAN IP address or remote hostname is not the same exception. Check window.isSecureContext and the APIs available in your browser or WebView. Do not disable PKCE or substitute insecure cryptography.

Related report: #1028.

How do I use multiple identity providers?

Use distinct configuration names rather than swapping settings under the same name. Give each configuration its own callback URLs and, in worker mode, a matching entry in OidcTrustedDomains.js.

In React, pass configurationName consistently to the provider and protected components, and select the name in hooks:

const { login, isAuthenticated } = useOidc('payments');
const { fetch: paymentsFetch } = useOidcFetch(undefined, 'payments');

Nesting providers does not change the hooks' default configuration name. Follow the named-configuration examples. Related questions: #1590 and #1283.

Should I use this client or a Backend for Frontend?

Choose based on your architecture and threat model, not a claim that either is always safer, cheaper, or simpler.

flowchart LR
    subgraph ClientSide["Browser client with worker token hiding"]
        App["Application JavaScript"] -->|"Token placeholders"| Worker["Service worker"]
        Worker <-->|"Token exchange"| ProviderA["OIDC provider"]
        Worker -->|"Access token"| APIA["API"]
    end
    subgraph ServerSide["Backend for Frontend"]
        Browser["Browser"] -->|"Session cookie"| BFF["BFF server"]
        BFF <-->|"Token exchange"| ProviderB["OIDC provider"]
        BFF -->|"Access token"| APIB["API"]
    end
Loading

This browser client can be used with a statically hosted application, without adding a dedicated authentication backend. You still need an identity provider, protected APIs, and appropriate CORS configuration. With worker token hiding enabled, access and refresh tokens remain in the browser's worker context; without the worker, they are accessible to application JavaScript.

A BFF keeps OAuth tokens on the server and typically gives the browser a session cookie. It requires backend hosting, session management, secure cookie configuration, and CSRF defenses. XSS can still cause authenticated actions in either architecture. This library does not implement a BFF or server-side access control.

Does the service worker protect me from XSS?

It reduces direct access to hidden tokens, but does not prevent XSS or CSRF. Malicious code running in your application can still make authenticated requests. Initializing OidcProvider early is not an XSS defense, and a CSP such as script-src 'self' does not guarantee that worker unregistration or iframe-based attacks are impossible.

Use a restrictive CSP suited to your deployment, safe rendering and input handling, reviewed dependencies, and narrowly scoped trusted destinations. Never embed a client secret in browser code. Do not render or log tokens. Your APIs must validate tokens and enforce authorization independently of client-side route guards.

What should I include in a bug report?

Include the package versions, browser/OS (and WebView host if applicable), whether a worker is enabled, relevant configuration names, sanitized configuration, reproduction steps, and expected versus actual behavior. For worker problems, include registration/scope information and whether the problem reproduces after a fresh registration in a test environment.

Use React's onEvent or the vanilla client's subscribeEvents to identify the failing phase. Record safe error codes and HTTP statuses, not complete event payloads. Remove tokens, authorization headers, cookies, authorization codes, PKCE verifiers, and personal data from screenshots, logs, or network exports before posting an issue.