### Example: Add Adapter-Backed Initial Access Token Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Example demonstrating how to add an adapter-backed initial access token and retrieve its value using the InitialAccessToken class. ```javascript new (provider.InitialAccessToken)({}).save().then(console.log); ``` -------------------------------- ### Example Supported Client Authentication Methods List Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md An example list of supported client authentication methods, including TLS-based methods that are available when mTLS is configured. ```javascript [ 'none', 'client_secret_basic', 'client_secret_post', 'client_secret_jwt', 'private_key_jwt', 'tls_client_auth', 'self_signed_tls_client_auth', // these methods are only available when features.mTLS is configured ] ``` -------------------------------- ### Example: Dynamically Issue Registration Access Token Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Example of a function to dynamically determine if a registration access token should be issued based on the request context. ```javascript // @param ctx - koa request context async issueRegistrationAccessToken(ctx) { return policyImplementation(ctx) } ``` -------------------------------- ### Example: Using provider.backchannelResult() Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Demonstrates how to use the provider.backchannelResult() method to complete the Consumption Device login process after end-user authentication. This method is part of the CIBA flow. ```javascript import * as oidc from 'oidc-provider'; const provider = new oidc.Provider(...); await provider.backchannelResult(...); ``` -------------------------------- ### Example: Fetching Attester Public Keys from JWKS Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md An example implementation for getAttestationSignaturePublicKey that fetches public keys from an attester's hosted JWKS endpoint using jose.createRemoteJWKSet. It handles multiple attesters and throws an error for unsupported issuers. ```js import * as jose from 'jose'; const attesters = new Map(Object.entries({ 'https://attester.example.com': jose.createRemoteJWKSet(new URL('https://attester.example.com/jwks')), })); function getAttestationSignaturePublicKey(ctx, iss, header, client) { if (attesters.has(iss)) return attesters.get(iss)(header); throw new Error('unsupported oauth-client-attestation issuer'); } ``` -------------------------------- ### Client Secret Encoding Example Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Demonstrates the correct form-encoding and base64 encoding for client secrets with special characters when using client_secret_basic authentication. ```javascript const client_id = "an:identifier"; const client_secret = "some secure & non-standard secret"; // After formencoding these two tokens const encoded_id = "an%3Aidentifier"; const encoded_secret = "some+secure+%26+non%2Dstandard+secret"; // Basic auth header format Authorization: Basic base64(encoded_id + ':' + encoded_secret) // Authorization: Basic YW4lM0FpZGVudGlmaWVyOnNvbWUrc2VjdXJlKyUyNitub24lMkRzdGFuZGFyZCtzZWNyZXQ= ``` -------------------------------- ### Supported Authorization Signing Algorithms List Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Example list of supported JWS 'alg' Algorithm values for signing JWT Authorization Responses (JARM). ```javascript [ 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'Ed25519', 'EdDSA', 'ML-DSA-44', 'ML-DSA-65', 'ML-DSA-87', // available in Node.js >= 24.7.0 'HS256', 'HS384', 'HS512', ] ``` -------------------------------- ### Example: Change Default Client Token Endpoint Auth Method Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Configures the default client token endpoint authentication method to 'client_secret_post'. ```javascript { token_endpoint_auth_method: 'client_secret_post' } ``` -------------------------------- ### Resource Server with JWT Signing and Audience Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Example configuration for a Resource Server requiring specific scopes, an audience value, a 2-hour access token TTL, and JWT signing with ES256. ```json { scope: 'api:read api:write', audience: 'resource-server-audience-value', accessTokenTTL: 2 * 60 * 60, // 2 hours accessTokenFormat: 'jwt', jwt: { sign: { alg: 'ES256' }, }, } ``` -------------------------------- ### Mounting OIDC Provider to an Express Application Source: https://github.com/panva/node-oidc-provider/blob/main/README.md This snippet demonstrates how to initialize and mount the OIDC provider to an existing Express.js application. Ensure the 'oidc-provider' package is installed. ```javascript import * as oidc from "oidc-provider"; const provider = new oidc.Provider("http://localhost:3000", { // refer to the documentation for other available configuration clients: [ { client_id: "foo", client_secret: "bar", redirect_uris: ["http://localhost:8080/cb"], // ... other client properties }, ], }); const server = provider.listen(3000, () => { console.log( "oidc-provider listening on port 3000, check http://localhost:3000/.well-known/openid-configuration", ); }); ``` -------------------------------- ### Handling Client Authentication Errors Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Provides an example of how to listen for and handle client authentication errors (e.g., 'invalid_client') using the provider's event emitter. This allows for logging or out-of-band notification of issues. ```javascript function handleClientAuthErrors({ headers: { authorization }, oidc: { body, client } }, err) { if (err.statusCode === 401 && err.message === "invalid_client") { // console.log(err); // save error details out-of-bands for the client developers, `authorization`, `body`, `client` // are just some details available, you can dig in ctx object for more. } } provider.on("grant.error", handleClientAuthErrors); provider.on("introspection.error", handleClientAuthErrors); provider.on("revocation.error", handleClientAuthErrors); ``` -------------------------------- ### Example: Supported JWS Signing Algorithm Values Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md A comprehensive list of supported JWS "alg" Algorithm values for signing, including RSA, ECDSA, and EdDSA variants. Note the availability of ML-DSA algorithms in newer Node.js versions. ```js [ 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'Ed25519', 'EdDSA', 'ML-DSA-44', 'ML-DSA-65', 'ML-DSA-87', // available in Node.js >= 24.7.0 ] ``` -------------------------------- ### Example: Change Default Client Response Type Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Configures the default client response types to 'code id_token' and includes 'implicit' grant type. ```javascript { response_types: ['code id_token'], grant_types: ['authorization_code', 'implicit'], } ``` -------------------------------- ### Example: Supported JWE Authorization Encryption Algorithm Values Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md A comprehensive list of supported JWE "alg" Algorithm values for encrypting JWT Authorization Responses (JARM), covering asymmetric RSAES, ECDH-ES, symmetric AES key wrapping, and direct encryption. ```js [ // asymmetric RSAES based 'RSA-OAEP', 'RSA-OAEP-256', 'RSA-OAEP-384', 'RSA-OAEP-512', // asymmetric ECDH-ES based 'ECDH-ES', 'ECDH-ES+A128KW', 'ECDH-ES+A192KW', 'ECDH-ES+A256KW', // symmetric AES key wrapping 'A128KW', 'A192KW', 'A256KW', 'A128GCMKW', 'A192GCMKW', 'A256GCMKW', // direct encryption 'dir', ] ``` -------------------------------- ### Example Supported Response Types List Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md An expanded list of supported response_type values, including combinations defined in OIDC Core 1.0 and OAuth 2.0 Multiple Response Type Encoding Practices. ```javascript [ 'code', 'id_token', 'id_token token', 'code id_token', 'code token', 'code id_token token', 'none', ] ``` -------------------------------- ### Add Arbitrary Claim to Access Token Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Demonstrates how to add a custom claim 'urn:idp:example:foo' with the value 'bar' to an Access Token during the token issuance process. ```javascript { async extraTokenClaims(ctx, token) { return { 'urn:idp:example:foo': 'bar', }; } } ``` -------------------------------- ### Example: Supported JWE Content Encryption Algorithm Values Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md A comprehensive list of supported JWE "enc" Content Encryption Algorithm values for encrypting JWT Authorization Responses (JARM), including CBC-HS and GCM modes. ```js [ 'A128CBC-HS256', 'A128GCM', 'A192CBC-HS384', 'A192GCM', 'A256CBC-HS512', 'A256GCM', ] ``` -------------------------------- ### Default Endpoint URL Paths Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Configuration object mapping authorization server endpoint names to their relative URL paths. All paths must start with a forward slash. ```js { authorization: '/auth', backchannel_authentication: '/backchannel', challenge: '/challenge', code_verification: '/device', device_authorization: '/device/auth', end_session: '/session/end', introspection: '/token/introspection', jwks: '/jwks', pushed_authorization_request: '/request', registration: '/reg', revocation: '/token/revocation', token: '/token', userinfo: '/me' } ``` -------------------------------- ### Register Extra Parameter with Validator Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Example of registering an 'origin' parameter with custom validation logic. It handles default values, required checks, and allowed values. ```javascript import { errors } from 'oidc-provider'; const extraParams = { async origin(ctx, value, client) { // @param ctx - koa request context // @param value - the `origin` parameter value (string or undefined) // @param client - client making the request if (hasDefaultOrigin(client)) { // assign default ctx.oidc.params.origin ||= value ||= getDefaultOrigin(client); } if (!value && requiresOrigin(ctx, client)) { // reject when missing but required throw new errors.InvalidRequest('"origin" is required for this request') } if (!allowedOrigin(value, client)) { // reject when not allowed throw new errors.InvalidRequest('requested "origin" is not allowed for this client') } } } ``` -------------------------------- ### Resource Server with Symmetrically Encrypted JWT Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Example configuration for a Resource Server with specific scopes, JWT access token format, and symmetric encryption using 'dir' algorithm and 'A128CBC-HS256' encryption. ```json { scope: 'api:read api:write', accessTokenFormat: 'jwt', jwt: { sign: false, encrypt: { alg: 'dir', enc: 'A128CBC-HS256', key: Buffer.from('f40dd9591646bebcb9c32aed02f5e610c2d15e1d38cde0c1fe14a55cf6bfe2d9', 'hex') }, } } ``` -------------------------------- ### Create Initial Access Token with Policies Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md After defining policy functions, create an Initial Access Token that will execute these policies. The policies are executed sequentially in the order they are provided in the array. ```javascript new (provider.InitialAccessToken)({ policies: ['my-policy', 'my-policy-2'] }).save().then(console.log); ``` -------------------------------- ### Default Device Info Extraction Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Extracts IP address and user-agent from the request context. This function is invoked to get device-specific information. ```javascript function deviceInfo(ctx) { return { ip: ctx.ip, ua: ctx.get('user-agent'), }; } ``` -------------------------------- ### Default processLoginHintToken Implementation Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default helper function to process the login_hint_token parameter. Throws an error indicating it's not implemented. ```javascript async function processLoginHintToken(ctx, loginHintToken) { // @param ctx - koa request context // @param loginHintToken - string value of the login_hint_token parameter throw new Error('features.ciba.processLoginHintToken not implemented'); } ``` -------------------------------- ### Default Resource Indicators Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Shows the default configuration for resource indicators, including placeholder functions that must be replaced before deployment. ```javascript { defaultResource: [AsyncFunction: defaultResource], // see expanded details below enabled: true, getResourceServerInfo: [AsyncFunction: getResourceServerInfo], // see expanded details below useGrantedResource: [AsyncFunction: useGrantedResource] // see expanded details below } ``` -------------------------------- ### Get Interaction Details (Koa) Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Retrieves details about an ongoing user interaction using the `provider.interactionDetails` helper with the Koa framework. Requires the interaction UID from the request. ```javascript // with koa router.get("/interaction/:uid", async (ctx, next) => { const details = await provider.interactionDetails(ctx.req, ctx.res); // ... }); ``` -------------------------------- ### OIDC Provider with Account Discovery Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Demonstrates how to configure the OIDC provider with a custom `findAccount` function for user authentication and claims retrieval. The `claims` function can return a Promise. ```javascript import * as oidc from "oidc-provider"; const provider = new oidc.Provider("http://localhost:3000", { async findAccount(ctx, id) { return { accountId: id, async claims(use, scope) { return { sub: id }; }, }; }, }); ``` -------------------------------- ### Get Interaction Details (Express) Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Retrieves details about an ongoing user interaction using the `provider.interactionDetails` helper with the Express framework. Requires the interaction UID from the request. ```javascript // with express expressApp.get("/interaction/:uid", async (req, res) => { const details = await provider.interactionDetails(req, res); // ... }); ``` -------------------------------- ### Modify Default Interaction Policy Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Demonstrates how to modify the default interaction policy by adding, removing, or getting prompts and checks. Use this to customize the user interaction flow. ```javascript import { interactionPolicy } from 'oidc-provider'; const { Prompt, Check, base } = interactionPolicy; const basePolicy = base() // basePolicy.get(name) => returns a Prompt instance by its name // basePolicy.remove(name) => removes a Prompt instance by its name // basePolicy.add(prompt, index) => adds a Prompt instance to a specific index, default is add the prompt as the last one // prompt.checks.get(reason) => returns a Check instance by its reason // prompt.checks.remove(reason) => removes a Check instance by its reason // prompt.checks.add(check, index) => adds a Check instance to a specific index, default is add the check as the last one ``` -------------------------------- ### Default RP-Initiated Logout Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default configuration for enabling RP-Initiated Logout. Includes default async functions for logout and post-logout success handling. ```javascript { enabled: true, logoutSource: [AsyncFunction: logoutSource], // see expanded details below postLogoutSuccessSource: [AsyncFunction: postLogoutSuccessSource] // see expanded details below } ``` -------------------------------- ### Get Interaction Result (Koa) Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Obtains the redirect URI for resuming an authorization request after an interaction using `provider.interactionResult` with Koa. The `result` object contains the interaction outcome. ```javascript // with koa router.post("/interaction/:uid", async (ctx, next) => { const redirectTo = await provider.interactionResult(ctx.req, ctx.res, result); ctx.body = { redirectTo }; }); ``` -------------------------------- ### Get Interaction Result (Express) Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Obtains the redirect URI for resuming an authorization request after an interaction using `provider.interactionResult` with Express. The `result` object contains the interaction outcome. ```javascript // with express expressApp.post("/interaction/:uid/login", async (req, res) => { const redirectTo = await provider.interactionResult(req, res, result); res.send({ redirectTo }); }); ``` -------------------------------- ### Define Registration and Management Policies Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Configure the `features.registration` object to define custom policy functions. These functions execute before standard client property validations during dynamic registration. You can set default properties, force specific values, or throw errors for validation failures. ```javascript { enabled: true, initialAccessToken: true, // to enable adapter-backed initial access tokens policies: { 'my-policy': function (ctx, properties) { // @param ctx - koa request context // @param properties - the client properties which are about to be validated // example of setting a default if (!('client_name' in properties)) { properties.client_name = generateRandomClientName(); } // example of forcing a value properties.userinfo_signed_response_alg = 'RS256'; // example of throwing a validation error if (someCondition(ctx, properties)) { throw new errors.InvalidClientMetadata('validation error message'); } }, 'my-policy-2': async function (ctx, properties) {}, }, } ``` -------------------------------- ### Default triggerAuthenticationDevice Implementation Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default helper function to initiate authentication and authorization on the end-user's Authentication Device. Throws an error indicating it's not implemented. ```javascript async function triggerAuthenticationDevice(ctx, request, account, client) { // @param ctx - koa request context // @param request - the BackchannelAuthenticationRequest instance // @param account - the account object retrieved by findAccount // @param client - the Client instance throw new Error('features.ciba.triggerAuthenticationDevice not implemented'); } ``` -------------------------------- ### Default renderError Function Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Provides a basic HTML structure for rendering error responses to the User-Agent. This default implementation is a starting point and should be customized for specific UI requirements. ```javascript async function renderError(ctx, out, error) { ctx.type = 'html'; ctx.body = ` oops! something went wrong

oops! something went wrong

${Object.entries(out).map(([key, value]) => `
${key}: ${htmlSafe(value)}
`).join('')}
`; } ``` -------------------------------- ### Add Custom Headers and Payload Claims to JWT Access Token Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Example of a customizer function to add custom headers and payload claims to a JWT format Access Token. ```javascript { customizers: { async jwt(ctx, token, jwt) { jwt.header = { foo: 'bar' }; jwt.payload.foo = 'bar'; } } } ``` -------------------------------- ### Custom Pre- and Post-Middleware Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Add custom middleware to execute logic before and after oidc-provider's route handlers. Use `ctx.path` for pre-processing and `ctx.oidc.route` for post-processing specific actions. ```javascript provider.use(async (ctx, next) => { /** pre-processing * you may target a specific action here by matching `ctx.path` */ console.log("pre middleware", ctx.method, ctx.path); await next(); /** post-processing * since internal route matching was already executed you may target a specific action here * checking `ctx.oidc.route`, the unique route names used are * * `authorization` * `backchannel_authentication` * `client_delete` * `client_update` * `client` * `code_verification` * `cors.device_authorization` * `cors.discovery` * `cors.introspection` * `cors.jwks` * `cors.pushed_authorization_request` * `cors.revocation` * `cors.token` * `cors.userinfo` * `device_authorization` * `device_resume` * `discovery` * `end_session_confirm` * `end_session_success` * `end_session` * `introspection` * `jwks` * `pushed_authorization_request` * `registration` * `resume` * `revocation` * `token` * `userinfo` */ console.log("post middleware", ctx.method, ctx.oidc.route); }); ``` -------------------------------- ### Mount oidc-provider to Fastify Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Mounts the oidc-provider callback to a Fastify application under the '/oidc' path. Requires @fastify/middie or @fastify/express. ```javascript // assumes fastify ^4.0.0 const fastify = new Fastify(); await fastify.register(require("@fastify/middie")); // or // await app.register(require('@fastify/express')); fastify.use("/oidc", provider.callback()); ``` -------------------------------- ### Default Account Loading Function Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Provides a default asynchronous function for loading account information and claims. This placeholder MUST be replaced with a deployment-specific implementation. It returns a basic account object with an accountId and a claims method. ```js async function findAccount(ctx, sub, token) { // @param ctx - koa request context // @param sub {string} - account identifier (subject) // @param token - is a reference to the token used for which a given account is being loaded, // is undefined in scenarios where claims are returned from authorization endpoint return { accountId: sub, // @param use {string} - can either be "id_token" or "userinfo", depending on // where the specific claims are intended to be put in // @param scope {string} - the intended scope, while oidc-provider will mask // claims depending on the scope automatically you might want to skip // loading some claims from external resources or through db projection etc. based on this // detail or not return them in ID Tokens but only UserInfo and so on // @param claims {object} - the part of the claims authorization parameter for either // "id_token" or "userinfo" (depends on the "use" param) // @param rejected {Array[String]} - claim names that were rejected by the end-user, you might // want to skip loading some claims from external resources or through db projection async claims(use, scope, claims, rejected) { return { sub }; }, }; } ``` -------------------------------- ### Default DPoP Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default settings for the DPoP feature, enabling it by default and disabling replay. ```js { allowReplay: false, enabled: true, nonceSecret: undefined, requireNonce: [Function: requireNonce] // see expanded details below } ``` -------------------------------- ### Default Statically Configured Clients Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md The default value for statically configured clients is an empty array, meaning no clients are pre-configured. ```js [] ``` -------------------------------- ### Register Custom Token Exchange Grant Type Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Example of registering a custom 'urn:ietf:params:oauth:grant-type:token-exchange' grant type with the OIDC provider. It defines allowed parameters and the handler function. ```javascript const parameters = [ "audience", "resource", "scope", "requested_token_type", "subject_token", "subject_token_type", "actor_token", "actor_token_type", ]; const allowedDuplicateParameters = ["audience", "resource"]; const grantType = "urn:ietf:params:oauth:grant-type:token-exchange"; async function tokenExchangeHandler(ctx, next) { // ctx.oidc.params holds the parsed parameters // ctx.oidc.client has the authenticated client // your grant implementation // see /lib/actions/grants for references on how to instantiate and issue tokens } provider.registerGrantType(grantType, tokenExchangeHandler, parameters, allowedDuplicateParameters); ``` -------------------------------- ### Enable Web Message Response Mode Source: https://github.com/panva/node-oidc-provider/wiki/pre5.0-changelog-(archive) Use this configuration to enable the experimental Web Message Response Mode feature. ```js const configuration = { features: { webMessageResponseMode: true } }; ``` -------------------------------- ### Configure Resource Server Client Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Configure a client intended solely for resource server operations, such as token introspection. Set 'response_types' to an empty array and 'grant_types' to an empty array. ```js { // ... rest of the client configuration response_types: [], grant_types: [] } ``` -------------------------------- ### Default Get Attestation Signature Public Key Helper Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md The default implementation for getAttestationSignaturePublicKey. This async function is invoked to verify the issuer identifier of a Client Attestation JWT and retrieve the public key for signature verification. It throws an error indicating it's not implemented. ```js async function getAttestationSignaturePublicKey(ctx, iss, header, client) { // @param ctx - koa request context // @param iss - Issuer Identifier from the Client Attestation JWT // @param header - Protected Header of the Client Attestation JWT // @param client - client making the request throw new Error('features.attestClientAuth.getAttestationSignaturePublicKey not implemented'); } ``` -------------------------------- ### Tax Data Access Authorization Details Type Validation Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Example of how to implement a custom validation function for 'tax_data' authorization details using Zod for schema validation. This ensures that the provided authorization details conform to the expected structure and constraints for tax data access. ```js import { z } from 'zod' const TaxData = z .object({ duration_of_access: z.number().int().positive(), locations: z .array( z.literal('https://taxservice.govehub.no.example.com'), ) .length(1), actions: z .array(z.literal('read_tax_declaration')) .length(1), periods: z .array( z.coerce .number() .max(new Date().getFullYear() - 1) .min(1997), ) .min(1), tax_payer_id: z.string().min(1), }) .strict() const configuration = { features: { richAuthorizationRequests: { enabled: true, // ... types: { tax_data: { validate(ctx, detail, client) { const { success: valid, error } = TaxData.safeParse(detail) if (!valid) { throw new InvalidAuthorizationDetails() } }, }, }, }, }, } ``` -------------------------------- ### Default Dynamic Client Registration Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default configuration for the Dynamic Client Registration (DCR) feature. DCR is disabled by default. ```javascript { enabled: false, idFactory: [Function: idFactory], initialAccessToken: false, issueRegistrationAccessToken: true, policies: undefined, secretFactory: [AsyncFunction: secretFactory] } ``` -------------------------------- ### Default Registration Management Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md The default configuration for `features.registrationManagement` has dynamic client registration management disabled and automatic rotation of the registration access token enabled. ```javascript { enabled: false, rotateRegistrationAccessToken: true } ``` -------------------------------- ### Finish Interaction with Login (Koa) Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Completes a user interaction, specifically a login prompt, using `provider.interactionFinished` with Koa. The `result` object should contain login details. ```javascript // with koa router.post('/interaction/:uid', async (ctx, next) => { return provider.interactionFinished(ctx.req, ctx.res, result); // result object below }); ``` -------------------------------- ### Supported Request Object Signing Algorithms Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Lists the JWS 'alg' Algorithm values supported for receiving signed Request Objects. This is the default configuration. ```javascript [ 'HS256', 'RS256', 'PS256', 'ES256', 'Ed25519', 'EdDSA' ] ``` ```javascript [ 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'Ed25519', 'EdDSA', 'ML-DSA-44', 'ML-DSA-65', 'ML-DSA-87', // available in Node.js >= 24.7.0 'HS256', 'HS384', 'HS512', ] ``` -------------------------------- ### Consent Prompt: Missing Resource Server Scopes Check Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md This check validates requested scopes for resource servers. It identifies scopes that are requested but not yet granted for each resource server and prompts for consent if any are missing. The missing scopes are detailed in `ctx.oidc[missingResourceScopes]`. ```javascript // checks resource server scopes new Check('rs_scopes_missing', 'requested scopes not granted', (ctx) => { const { oidc } = ctx; let missing; for (const [indicator, resourceServer] of Object.entries(ctx.oidc.resourceServers)) { const encounteredScopes = new Set(oidc.grant.getResourceScopeEncountered(indicator).split(' ')); const requestedScopes = ctx.oidc.requestParamScopes; const availableScopes = resourceServer.scopes; for (const scope of requestedScopes) { if (availableScopes.has(scope) && !encounteredScopes.has(scope)) { missing ||= {}; missing[indicator] ||= []; missing[indicator].push(scope); } } } if (missing && Object.keys(missing).length) { ctx.oidc[missingResourceScopes] = missing; return Check.REQUEST_PROMPT; } return Check.NO_NEED_TO_PROMPT; }, ({ oidc }) => ({ missingResourceScopes: oidc[missingResourceScopes] })), ``` -------------------------------- ### Default Development Interactions Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Shows the default configuration for the 'devInteractions' feature, which enables development-only interaction views for rapid prototyping. This feature must be disabled in production deployments. ```javascript { enabled: true } ``` -------------------------------- ### Default Attest Client Auth Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Shows the default configuration object for the features.attestClientAuth option. Note that 'assertAttestationJwtAndPop' and 'getAttestationSignaturePublicKey' are async functions and 'enabled' defaults to false. ```js { ack: undefined, assertAttestationJwtAndPop: [AsyncFunction: assertAttestationJwtAndPop], // see expanded details below challengeSecret: undefined, enabled: false, getAttestationSignaturePublicKey: [AsyncFunction: getAttestationSignaturePublicKey] // see expanded details below } ``` -------------------------------- ### Default getCertificate Helper Function Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md The default implementation for the getCertificate helper function. This function must be replaced with a custom implementation to retrieve the client certificate used in the request. ```javascript function getCertificate(ctx) { throw new Error('features.mTLS.getCertificate function not configured'); } ``` -------------------------------- ### Default External Signing Support Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default configuration for the External Signing Support feature. This feature enables the use of external cryptographic services for signing operations. ```js { ack: undefined, enabled: false } ``` -------------------------------- ### Mount oidc-provider to Hapi Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Mounts the oidc-provider callback to a Hapi application, handling URL rewriting for the '/oidc' path prefix. Requires @hapi/hapi ^21.0.0. ```javascript // assumes @hapi/hapi ^21.0.0 const callback = provider.callback(); hapiApp.route({ path: `/oidc/{any*}\\`, method: "*", config: { payload: { output: "stream", parse: false } }, async handler({ raw: { req, res } }, h) { req.originalUrl = req.url; req.url = req.url.replace("/oidc", ""); callback(req, res); await once(res, "finish"); req.url = req.url.replace("/", "/oidc"); delete req.originalUrl; return res.writableEnded ? h.abandon : h.continue; }, }); ``` -------------------------------- ### Default Success Page HTML Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Provides the HTML source for the success page displayed after the device flow completes. It includes a success message and optionally the client name. ```javascript async function successSource(ctx) { // @param ctx - koa request context const display = ctx.oidc.client.clientName ? `with ${htmlSafe(ctx.oidc.client.clientName)}` : ''; ctx.body = ` Sign-in Success

Sign-in Success

Your sign-in ${display} was successful, you can now close this page.

`; } ``` -------------------------------- ### Finish Interaction with Login (Express) Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Completes a user interaction, specifically a login prompt, using `provider.interactionFinished` with Express. The `result` object should contain login details. ```javascript // with express expressApp.post('/interaction/:uid/login', async (req, res) => { return provider.interactionFinished(req, res, result); // result object below }); ``` -------------------------------- ### Encode client credentials for client_secret_basic Source: https://github.com/panva/node-oidc-provider/wiki/FAQ Demonstrates the required form-encoding for client_id and client_secret before base64 encoding for the Authorization header. ```javascript const client_id = 'an:identifier'; const client_secret = 'some secure & non-standard secret'; // After formencoding these two tokens const encoded_id = 'an%3Aidentifier'; const encoded_secret = 'some+secure+%26+non-standard+secret'; // Basic auth header format Authorization: Basic base64(encoded_id + ':' + encoded_secret) // Authorization: Basic YW4lM0FpZGVudGlmaWVyOnNvbWUrc2VjdXJlKyUyNitub24tc3RhbmRhcmQrc2VjcmV0 ``` -------------------------------- ### Default Supported Client Authentication Methods Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Specifies the client authentication methods supported by the authorization server. Includes common methods like 'client_secret_basic' and 'private_key_jwt'. ```javascript [ 'client_secret_basic', 'client_secret_jwt', 'client_secret_post', 'private_key_jwt', 'none' ] ``` -------------------------------- ### Handle Client Authentication Errors Source: https://github.com/panva/node-oidc-provider/wiki/pre5.0-changelog-(archive) Configure error handling for client authentication failures. Errors related to parsing are now 400 Bad Request, while authentication check errors are 401 Unauthorized. This listener helps capture and manage these errors out-of-band. ```javascript function handleClientAuthErrors(err, { headers: { authorization }, oidc: { body, client } }) { if (err instanceof Provider.errors.InvalidClientAuth) { // save error details out-of-bands for the client developers, `authorization`, `body`, `client` // are just some details available, you can dig in ctx object for more. console.log(err); } } provider.on('grant.error', handleClientAuthErrors); provider.on('introspection.error', handleClientAuthErrors); provider.on('revocation.error', handleClientAuthErrors); ``` -------------------------------- ### Default mTLS Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Shows the default configuration object for the features.mTLS option. Note that helper functions are placeholders and must be replaced. ```javascript { certificateAuthorized: [Function: certificateAuthorized], // see expanded details below certificateBoundAccessTokens: false, certificateSubjectMatches: [Function: certificateSubjectMatches], // see expanded details below enabled: false, getCertificate: [Function: getCertificate], // see expanded details below selfSignedTlsClientAuth: false, tlsClientAuth: false } ``` -------------------------------- ### Default deviceFlow Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default configuration for the OAuth 2.0 Device Authorization Grant. Key helper functions are placeholders and require customization. The feature is disabled by default. ```javascript { charset: 'base-20', deviceInfo: [Function: deviceInfo], // see expanded details below enabled: false, mask: '****-****', successSource: [AsyncFunction: successSource], // see expanded details below userCodeConfirmSource: [AsyncFunction: userCodeConfirmSource], // see expanded details below userCodeInputSource: [AsyncFunction: userCodeInputSource] // see expanded details below } ``` -------------------------------- ### Configure Client Credentials Grant Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Configure a client to exclusively use the Client Credentials grant type. Set 'response_types' to an empty array as these clients do not use the authorization endpoint. ```js { // ... rest of the client configuration response_types: [], grant_types: ['client_credentials'] } ``` -------------------------------- ### Default Cache Duration Configuration for CIMD Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default cache duration settings for fetched client metadata documents. Specifies minimum and maximum cache duration bounds in seconds. ```js { max: 86400, min: 30 } ``` -------------------------------- ### Runtime TTL Resolution for Access Tokens Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Configure the 'ttl' option to dynamically resolve the Time-To-Live (TTL) for access tokens at runtime. This function must return a numeric value in seconds and can utilize context, token, and client information. ```javascript { ttl: { AccessToken(ctx, token, client) { // return a Number (in seconds) for the given token (second argument), the associated client is // passed as a third argument // Tip: if the values are entirely client based memoize the results return resolveTTLfor(token, client); }, }, } ``` -------------------------------- ### Initial Access Token Events Source: https://github.com/panva/node-oidc-provider/blob/main/docs/events.md Events related to the destruction and saving of initial access tokens. ```APIDOC ## Initial Access Token Events ### Description Events concerning the initial access token. ### Events - `initial_access_token.destroyed`: Triggered whenever an initial access token is destroyed. It provides the `token`. - `initial_access_token.saved`: Triggered whenever an initial access token is saved. It provides the `token`. ``` -------------------------------- ### Default Client ID Metadata Document Configuration Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default configuration for the Client ID Metadata Document feature. This feature allows resolving client metadata from HTTPS URLs. ```js { ack: undefined, allowClient: [AsyncFunction: allowClient], allowFetch: [AsyncFunction: allowFetch], cacheDuration: { max: 86400, min: 30 }, enabled: false } ``` -------------------------------- ### Default User Code Input Source for Device Flow Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md This is the default HTML source rendered for the user code input prompt in the device authorization flow. It includes basic styling and error handling messages. ```js async function userCodeInputSource(ctx, form, out, err) { // @param ctx - koa request context // @param form - form source (id="op.deviceInputForm") to be embedded in the page and submitted // by the End-User. // @param out - if an error is returned the out object contains details that are fit to be // rendered, i.e. does not include internal error messages // @param err - error object with an optional userCode property passed when the form is being // re-rendered due to code missing/invalid/expired let msg; if (err && (err.userCode || err.name === 'NoCodeError')) { msg = '

The code you entered is incorrect. Try again

'; } else if (err && err.name === 'AbortedError') { msg = '

The Sign-in request was interrupted

'; } else if (err) { msg = '

There was an error processing your request

'; } else { msg = '

Enter the code displayed on your device

'; } ctx.body = ` Sign-in

Sign-in

${msg} ${form}
`; } ``` -------------------------------- ### Default User Code Confirmation Page HTML Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Renders the HTML for the device login confirmation prompt. It displays the client name, the user code, and provides options to continue or abort. ```javascript async function userCodeConfirmSource(ctx, form, client, deviceInfo, userCode) { // @param ctx - koa request context // @param form - form source (id="op.deviceConfirmForm") to be embedded in the page and // submitted by the End-User. // @param deviceInfo - device information from the device_authorization_endpoint call // @param userCode - formatted user code by the configured mask const display = htmlSafe(ctx.oidc.client.clientName || ctx.oidc.client.clientId); ctx.body = ` Device Login Confirmation

Confirm Device

${display}

The following code should be displayed on your device

${userCode}

If you did not initiate this action, the code does not match or are unaware of such device in your possession please close this window or click abort.

${form}
`; } ``` -------------------------------- ### Registering Koa Helmet Middleware Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Integrate the koa-helmet middleware to add security headers to your application. Ensure helmet is imported before use. ```javascript import helmet from "koa-helmet"; provider.use(helmet()); ``` -------------------------------- ### Default allowClient Function for CIMD Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Default implementation for the allowClient helper function. This function is invoked before a client resolved from a metadata document is used. ```js async allowClient(ctx, client) { return true; } ``` -------------------------------- ### Default verifyUserCode Implementation Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md The default implementation for verifying the user_code parameter. It throws an error indicating that the feature is not implemented, requiring a custom implementation. ```javascript async function verifyUserCode(ctx, account, userCode) { // @param ctx - koa request context // @param account - // @param userCode - string value of the user_code parameter, when not provided it is undefined throw new Error('features.ciba.verifyUserCode not implemented'); } ``` -------------------------------- ### Acknowledge Experimental Feature Source: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md Demonstrates how to acknowledge an experimental feature to suppress warnings and prevent errors due to unacknowledged breaking changes. The 'ack' property should be set to the specific version string provided in the warning notice. ```javascript import * as oidc from 'oidc-provider' new oidc.Provider('http://localhost:3000', { features: { webMessageResponseMode: { enabled: true, }, }, }); ``` ```javascript // The above code produces this NOTICE // NOTICE: The following experimental features are enabled and their implemented version not acknowledged // NOTICE: - OAuth 2.0 Web Message Response Mode - draft 01 (Acknowledging this feature's implemented version can be done with the value 'individual-draft-01') // NOTICE: Breaking changes between experimental feature updates may occur and these will be published as MINOR semver oidc-provider updates. // NOTICE: You may disable this notice and be warned when breaking updates occur by acknowledging the current experiment's version. See the documentation for more details. new oidc.Provider('http://localhost:3000', { features: { webMessageResponseMode: { enabled: true, ack: 'individual-draft-01', }, }, }); // No more NOTICE, at this point if the experimental was updated and contained no breaking // changes, you're good to go, still no NOTICE, your code is safe to run. // Now let's assume you upgrade oidc-provider version and it includes a breaking change in // this experimental feature new oidc.Provider('http://localhost:3000', { features: { webMessageResponseMode: { enabled: true, ack: 'individual-draft-01', }, }, }); // Thrown: // Error: An unacknowledged version of an experimental feature is included in this oidc-provider version. ```