### Install and test the library Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/CONTRIBUTING.md Install dependencies and run the test suite for the library. ```bash npm install npm test ``` -------------------------------- ### Run playground app Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/CONTRIBUTING.md Start the playground app in the examples workspace. ```shell npm run dev --workspace=packages/examples ``` -------------------------------- ### Install express-oauth2-jwt-bearer with npm Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/README.md Install the package in your project directory using npm. ```shell npm install express-oauth2-jwt-bearer ``` -------------------------------- ### Example: Allow up to 60 seconds of clock skew Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Example configuration for `iatLeeway: 60`, allowing up to 60 seconds of client/server clock skew. Applied only when `enabled: true` and a DPoP proof is present. ```typescript // Allow up to 60 seconds of client/server clock skewauth({ dpop: { enabled: true, iatLeeway: 60 } }) ``` -------------------------------- ### Example: Reject proofs older than 2 minutes Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Example configuration for `iatOffset: 120`, rejecting DPoP proofs older than 2 minutes. Applied only when `enabled: true` and a DPoP proof is present. ```typescript // Reject proofs older than 2 minutesauth({ dpop: { enabled: true, iatOffset: 120 } }) ``` -------------------------------- ### Example: Accept both Bearer and DPoP (default) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Example configuration for `enabled: true` with `required: false`, which is the default behavior. Accepts both Bearer and DPoP authorization schemes. ```typescript // Accept both Bearer and DPoP (default):auth({ dpop: { enabled: true, required: false } }) ``` -------------------------------- ### Example: DPoP-only Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Example configuration for `required: true`, requiring DPoP tokens exclusively when DPoP is enabled. Non-DPoP tokens are rejected. ```typescript // DPoP-only:auth({ dpop: { enabled: true, required: true } }) ``` -------------------------------- ### Example: Bearer-only (DPoP disabled) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Example configuration for `enabled: false`, which disables DPoP support and only allows the Bearer scheme. ```typescript // Bearer-only (DPoP disabled):auth({ dpop: { enabled: false } }) ``` -------------------------------- ### Root workspace commands (npm install, test, lint, build, docs) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/references/commands.md Run these from the repository root to operate on all workspaces. Requires npm >= 7.14. `npm run docs` generates TypeDoc API docs into docs/ using typedoc with typedoc.js options. ```bash npm install # install all workspace deps (npm >= 7.14 required) npm test # run every package's test suite (npm test --workspaces) npm run lint # lint every package (npm run lint --workspaces) npm run build # build every package (npm run build --workspaces) npm run docs # generate TypeDoc API docs into docs/ (typedoc --options typedoc.js) ``` -------------------------------- ### Cache configuration for mcd Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Override the default cache settings for OIDC discovery metadata and JWKS responses. The default is 100 entries with a 10-minute TTL each; this example sets 50 entries and a 5-minute TTL for both. ```javascript auth({ mcd: { issuers: [...] }, audience: 'https://your-api.com', cache: { discovery: { maxEntries: 50, ttl: 300_000 }, // 5 minutes jwks: { maxEntries: 50, ttl: 300_000 }, } }) ``` -------------------------------- ### Per-package workspace commands (npm test, lint, build, dev) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/references/commands.md Run a single workspace with `--workspace=`. The examples package uses `npm run dev` to run the playground app. Build notes: `oauth2-bearer` and `access-token-jwt` compile with tsc; `express-oauth2-jwt-bearer` bundles with Rollup. Every package's prebuild runs `rimraf dist` first. ```bash npm test --workspace=express-oauth2-jwt-bearer # jest test --coverage npm run lint --workspace=access-token-jwt # eslint --fix --ext .ts ./src npm run build --workspace=oauth2-bearer # tsc (prebuild: rimraf dist) npm run dev --workspace=packages/examples # run the examples playground app ``` -------------------------------- ### Bad example: bare Error with double quotes Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/references/code-style.md Shows the discouraged style: bare Error, double quotes, and missing type annotations. The comment notes that double quotes fail Prettier and that RFC 6750 error types should be used. ```typescript export function requireAudience(audience) { // missing types return (payload) => { if (payload.aud !== audience) { throw new Error("bad aud"); // use the RFC 6750 error types; double quotes fail Prettier } }; } ``` -------------------------------- ### Accept anonymous callers and branch in the handler Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use this snippet to accept anonymous callers and branch in the handler by checking if 'req.auth.payload.sub' starts with 'anon@'. Requires the Anonymous Sessions add-on to be enabled on your Auth0 tenant. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use(auth({ issuerBaseURL: 'https://YOUR_DOMAIN', audience: 'https://api.example.com', })); app.get('/cart', (req, res) => { const isAnonymous = req.auth.payload.sub?.startsWith('anon@'); // serve differently based on whether the caller is anonymous }); ``` -------------------------------- ### Block all anonymous callers globally with auth() Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use this snippet to reject all anonymous callers globally by adding a validator on the 'sub' claim that fails when it starts with 'anon@'. Requires the Anonymous Sessions add-on to be enabled on your Auth0 tenant. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuerBaseURL: 'https://YOUR_DOMAIN', audience: 'https://api.example.com', validators: { sub: (sub) => !sub.startsWith('anon@'), }, }) ); ``` -------------------------------- ### Good example: typed OAuth error with single quotes Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/references/code-style.md Shows the preferred style: typed OAuth error from 'oauth2-bearer', single quotes, and an option-driven factory. Throws InvalidTokenError when the audience claim does not match. ```typescript import { InvalidTokenError } from 'oauth2-bearer'; export const requireAudience = (audience: string) => (payload: JWTPayload) => { if (payload.aud !== audience) { throw new InvalidTokenError('Unexpected token audience'); } }; ``` -------------------------------- ### Block anonymous callers on specific routes with claimCheck() Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use this snippet to block anonymous callers on specific routes by adding a claimCheck middleware that rejects tokens whose 'sub' starts with 'anon@'. Requires the Anonymous Sessions add-on to be enabled on your Auth0 tenant. ```javascript const { auth, claimCheck } = require('express-oauth2-jwt-bearer'); app.use(auth({ issuerBaseURL: 'https://YOUR_DOMAIN', audience: 'https://api.example.com', })); app.get('/checkout', claimCheck((payload) => !payload.sub?.startsWith('anon@')), (req, res) => { /* authenticated callers only */ } ); ``` -------------------------------- ### claimIncludes usage with auth middleware Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/functions/claimIncludes.html Checks a token's claim to include all given JSONPrimitive values (string, number, boolean, or null). Raises a 401 invalid_token error if the claim does not include all the given values. The example shows protecting an /admin/edit route requiring both 'admin' and 'editor' roles. ```javascript app.use(auth());app.get('/admin/edit', claimIncludes('role', 'admin', 'editor'), (req, res) => { ... }); ``` -------------------------------- ### Accessing auth result properties in a route Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/functions/auth.html After successful authentication, the request object gets an auth property containing the decoded JWT header, payload, and raw token. Use this snippet to access those values in a protected route. ```javascript app.get('/foo', auth(), (req, res, next) => { const auth = req.auth; auth.header; // The decoded JWT header. auth.payload; // The decoded JWT payload. auth.token; // The raw JWT token.}); ``` -------------------------------- ### getCertificate: Extract client certificate from nginx header Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/types/GetCertificate.html Resolves the client certificate presented on the TLS connection for the current request, used to validate certificate-bound (mTLS, RFC 8705) access tokens. This example handles nginx forwarding URL-encoded PEM in a header, returning undefined when no certificate is present. Supplying this resolver sets mtls.enabled to true by default; set mtls: { enabled: false } explicitly to keep mTLS off. ```TypeScript // nginx forwarding URL-encoded PEM in a header: getCertificate: (req) => { const pem = req.headers['client-certificate']; return typeof pem === 'string' ? decodeURIComponent(pem) : undefined; } ``` -------------------------------- ### Use auth middleware with environment variables Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/README.md Initialize the auth middleware using the environment variables. The library requires issuerBaseURL and audience. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use(auth()); ``` -------------------------------- ### Initialize auth middleware with explicit options Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/README.md Configure the auth middleware by passing issuerBaseURL and audience directly. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', }) ); ``` -------------------------------- ### Run lint command Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/CONTRIBUTING.md Run the linter before pushing changes. ```bash npm run lint ``` -------------------------------- ### Run tests with npm test Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/references/testing.md Commands to run the test suite from the repository root. The first runs all packages; the second runs a single package; the third skips the coverage gate while iterating; the fourth runs a single test file (or cd into the package and run npx jest). ```bash npm test # all packages npm test --workspace=express-oauth2-jwt-bearer # one package npm test --workspace=access-token-jwt -- --coverage=false # skip the coverage gate while iterating npx jest test/index.test.ts --workspace=... # a single file (or cd into the package and run npx jest) ``` -------------------------------- ### Lint all workspaces Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/CLAUDE.md Runs ESLint with --fix over each source directory in all workspaces. ```bash npm run lint # lint all workspaces (ESLint --fix over each src) ``` -------------------------------- ### Configure auth with static public key (PEM, JWK, or JWKS) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/README.md Use this when you already have the issuer's public key and want to skip OIDC discovery or a remote JWKS endpoint. Accepted formats: PEM-encoded SPKI string, a single JWK object, or an inline JWK Set. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); // PEM-encoded SPKI public key app.use( auth({ issuer: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----', tokenSigningAlg: 'RS256', }) ); // Inline JWK app.use( auth({ issuer: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', publicKey: { kty: 'EC', crv: 'P-256', x: '...', y: '...', alg: 'ES256' }, }) ); // Inline JWK Set app.use( auth({ issuer: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', publicKey: { keys: [{ kty: 'RSA', n: '...', e: 'AQAB', alg: 'RS256', kid: '...' }] }, }) ); ``` -------------------------------- ### Set environment variables for issuer and audience Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/README.md Define the required ISSUER_BASE_URL and AUDIENCE environment variables for the SDK. ```shell ISSUER_BASE_URL=https://YOUR_ISSUER_DOMAIN AUDIENCE=https://my-api.com ``` -------------------------------- ### Accept both Bearer and DPoP tokens (default) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Configures the middleware to accept both Bearer and DPoP tokens (default behavior). Requests using DPoP must include both the Authorization and DPoP headers as shown. ```js const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', dpop: { enabled: true, // Enables DPoP support required: false // Accepts both Bearer and DPoP tokens (default) } }) ); app.get('/api/resource', (req, res) => { res.send('Access granted'); }); ``` ```http Authorization: DPoP eyJhbGciOiJFUzI1NiIsInR5cCI6... DPoP: eyJhbGciOiJkcG9wIiwidHlwIjoi... ``` -------------------------------- ### Static Public Key Verification with PEM-encoded SPKI string Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use this when you have the issuer's public key in PEM SPKI format and want to skip OIDC discovery and remote JWKS fetches. `tokenSigningAlg` is required because the algorithm cannot be inferred from the key material. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuer: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----', tokenSigningAlg: 'RS256', }) ); ``` -------------------------------- ### Run workspace commands Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/CONTRIBUTING.md Commands to run in the context of a workspace using npm workspaces. Requires npm >= 7.14. ```shell # install jose on access-token-jwt npm run install jose --workspace=access-token-jwt # build oauth2-bearer npm run build --workspace=oauth2-bearer # run all tests npm test --workspaces # you can also use the `npm test` script ``` -------------------------------- ### Static Public Key Verification with Inline JWK Set Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use this when you have an inline JWK Set and want to support key rotation. Key selection uses the token's `kid` header matched against each key's `kid` field. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuer: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', publicKey: { keys: [ { kty: 'RSA', n: '...', e: 'AQAB', alg: 'RS256', kid: 'key-1' }, { kty: 'RSA', n: '...', e: 'AQAB', alg: 'RS256', kid: 'key-2' }, ], }, }) ); ``` -------------------------------- ### Static list of issuers with mcd Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Configure the auth middleware with a static list of allowed issuer URLs for multiple custom domains. The `mcd` option is mutually exclusive with `issuerBaseURL`; all issuers must belong to the same Authorization Server. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ mcd: { issuers: [ 'https://brand-a.example.com', 'https://brand-b.example.com', ] }, audience: 'https://your-api.com' }) ); ``` -------------------------------- ### In-memory DPoP jti cache (development/single instance) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Middleware that validates DPoP jti uniqueness using an in-memory Map. It parses the DPoP proof header, checks for existing jti, and rejects reused proofs with a 401 error. The cache stores jti with a TTL based on the proof's iat plus 330 seconds (default validity window 300s + 30s leeway). ```javascript const express = require('express'); const { auth } = require('express-oauth2-jwt-bearer'); const jtiCache = new Map(); const validateDPoPJti = (req, res, next) => { const dpopProof = req.headers['dpop']; if (!dpopProof) return next(); const [, payloadB64] = dpopProof.split('.'); const payload = JSON.parse( Buffer.from(payloadB64, 'base64url').toString() ); const { jti, iat } = payload; if (jtiCache.has(jti)) { return res.status(401).json({ error: 'invalid_token', error_description: 'DPoP proof has already been used' }); } // Default validity window: 300s + 30s jtiCache.set(jti, (iat + 330) * 1000); next(); }; const app = express(); app.use(auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', dpop: { enabled: true } })); app.use(validateDPoPJti); app.get('/api/protected', (req, res) => { res.json({ message: 'Access granted' }); }); ``` -------------------------------- ### Dynamic resolver for mcd issuers Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use a resolver function to select allowed issuers based on request context. The resolver must return an array of issuer URLs or config objects; `context.headers` and `context.url` are request-derived and must only be used to select from a hard-coded allowlist. The `x-tenant-id` header must be set by trusted upstream infrastructure, not the client. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); // ALLOWED_ISSUERS is a hard-coded allowlist — never build this from request input. const ALLOWED_ISSUERS = { 'tenant-a': ['https://brand-a.example.com'], 'tenant-b': ['https://brand-b.example.com'], }; app.use( auth({ mcd: { issuers: async (context) => { // x-tenant-id must be set by trusted upstream middleware, not the client. const tenantId = context.headers['x-tenant-id']; const issuers = ALLOWED_ISSUERS[tenantId]; if (!issuers) throw new Error('Unknown tenant'); return issuers; } }, audience: 'https://your-api.com' }) ); ``` -------------------------------- ### Static Public Key Verification with Single JWK object Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use this when you have a single JWK object. The `alg` field in the JWK is used for algorithm selection; if omitted, provide `tokenSigningAlg`. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuer: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', publicKey: { kty: 'EC', crv: 'P-256', x: '...', y: '...', alg: 'ES256' }, }) ); ``` -------------------------------- ### Redis-based DPoP jti cache (production/multi-instance) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Middleware that validates DPoP jti uniqueness using a shared Redis cache. It checks if the jti exists, rejects reused proofs with a 401 and WWW-Authenticate header, and stores the jti with a TTL matching the proof's validity window. Suitable for multi-instance deployments. ```javascript const express = require('express'); const { auth } = require('express-oauth2-jwt-bearer'); const Redis = require('ioredis'); const redis = new Redis({ host: process.env.REDIS_HOST || 'localhost', port: process.env.REDIS_PORT || 6379, }); const validateDPoPJtiWithRedis = async (req, res, next) => { const dpopProof = req.headers['dpop']; if (!dpopProof) { return next(); } try { const [, payloadB64] = dpopProof.split('.'); const payload = JSON.parse( Buffer.from(payloadB64, 'base64url').toString() ); const { jti, iat } = payload; // Check if jti exists in Redis const exists = await redis.exists(`dpop:jti:${jti}`); if (exists) { return res.status(401) .set('WWW-Authenticate', 'DPoP error="use_dpop_nonce", error_description="DPoP proof has already been used"') .json({ error: 'use_dpop_nonce', error_description: 'DPoP proof has already been used' }); } // Store jti with TTL matching the proof's validity window const now = Math.floor(Date.now() / 1000); const ttlSeconds = Math.max(1, (iat + 330) - now); // iat + iatOffset + iatLeeway await redis.setex(`dpop:jti:${jti}`, ttlSeconds, '1'); next(); } catch (err) { next(err); } }; const app = express(); app.use(auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', dpop: { enabled: true } })); app.use(validateDPoPJtiWithRedis); app.get('/api/protected', (req, res) => { res.json({ message: 'Access granted' }); }); ``` -------------------------------- ### Resolve client certificate with getCertificate Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Configure the auth middleware with a getCertificate function that reads the client certificate from a request header (e.g., 'client-certificate') and URL-decodes it. Supplying getCertificate automatically enables mTLS (mtls.enabled defaults to true). ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', getCertificate: (req) => { // nginx forwarding URL-encoded PEM in a header (see "Terminating TLS with a proxy" below): const pem = req.headers['client-certificate']; return typeof pem === 'string' ? decodeURIComponent(pem) : undefined; }, }) ); ``` -------------------------------- ### iatLeeway Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Allowed clock skew (in seconds) for future-dated `iat` values. A small positive leeway prevents valid proofs from being rejected when `iat` appears a bit in the future. This is applied only when `enabled: true` and a DPoP proof is present. ```APIDOC ## iatLeeway ### Description Allowed clock skew (in seconds) for future-dated `iat` values. Some clients have slightly skewed clocks; a small positive leeway prevents valid proofs from being rejected when `iat` appears a bit in the future. This is applied only when `enabled: true` and a DPoP proof is present. ### Default ```ts 30 // 30 seconds ``` ### Example ```ts // Allow up to 60 seconds of client/server clock skew auth({ dpop: { enabled: true, iatLeeway: 60 } }) ``` ``` -------------------------------- ### Run all workspace test suites Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/CLAUDE.md Runs all Jest test suites across workspaces. HTTP requests are mocked with nock, so tests are safe to run. ```bash npm test # run all workspace test suites (Jest, safe — HTTP is nocked) ``` -------------------------------- ### iatOffset Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Maximum accepted age (in seconds) for a DPoP proof's `iat` claim. Proofs older than `iatOffset` (relative to current server time) are rejected. This is applied only when `enabled: true` and a DPoP proof is present. ```APIDOC ## iatOffset ### Description Maximum accepted age (in seconds) for a DPoP proof's `iat` claim. Proofs older than `iatOffset` (relative to current server time) are rejected. This is applied only when `enabled: true` and a DPoP proof is present. ### Default ```ts 300 // 5 minutes ``` ### Example ```ts // Reject proofs older than 2 minutes auth({ dpop: { enabled: true, iatOffset: 120 } }) ``` ``` -------------------------------- ### Configure auth for HS256 symmetric tokens Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/README.md Configure the auth middleware for JWTs signed with symmetric algorithms like HS256, using a shared secret. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuer: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', secret: 'YOUR SECRET', tokenSigningAlg: 'HS256', }) ); ``` -------------------------------- ### Customize DPoP validation behavior Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Customizes DPoP validation behavior by setting iatOffset (maximum proof age, default 300 seconds) and iatLeeway (clock skew tolerance, default 30 seconds). ```js const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', dpop: { enabled: true, required: true, iatOffset: 300, // Reject proofs older than 5 minutes iatLeeway: 30, // Allow 30s clock skew } }) ); ``` -------------------------------- ### claimEquals Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/index.html Middleware for checking if a claim equals a specific value. ```APIDOC ## claimEquals ### Description Creates a middleware function that checks if a specific claim in the JWT payload equals a given value. ### Usage ```javascript const { claimEquals } = require('express-oauth2-jwt-bearer'); app.use(claimEquals('role', 'admin')); ``` ### Parameters - **claim** (string) - Required - The name of the claim to check. - **value** (any) - Required - The expected value of the claim. ### Returns - Express middleware function. ``` -------------------------------- ### enabled Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Enables DPoP support. When enabled, requests can use the DPoP authorization scheme and the middleware will validate proofs. When disabled, only the Bearer scheme is supported and DPoP-bound tokens are accepted with the cnf claim ignored. ```APIDOC ## enabled ### Description Enables DPoP support. When `enabled: true`, requests can use the DPoP authorization scheme (`Authorization: DPoP …` plus a `DPoP` proof header), and the middleware will validate proofs. When `enabled: false`, only the Bearer scheme is supported, any token sent with the DPoP scheme is rejected, DPoP-bound tokens sent with Bearer are accepted (the `cnf` claim is ignored), and any `DPoP` proof header is ignored. ### Default ```ts true ``` ### Example ```ts // Accept both Bearer and DPoP (default): auth({ dpop: { enabled: true, required: false } }) ``` ### Example ```ts // Bearer-only (DPoP disabled): auth({ dpop: { enabled: false } }) ``` ``` -------------------------------- ### Default value for iatOffset property Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Default value for the `iatOffset` property of DPoPOptions. Maximum accepted age for a DPoP proof's `iat` claim is 300 seconds (5 minutes). Proofs older than this are rejected. Applied only when `enabled: true` and a DPoP proof is present. ```typescript 300 // 5 minutes ``` -------------------------------- ### auth Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/index.html Middleware for validating JWTs in Express applications. ```APIDOC ## auth ### Description Middleware for validating JWTs in Express applications. It verifies the token's signature, expiration, issuer, and audience, and attaches the authentication result to the request. ### Usage ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use(auth(options)); ``` ### Parameters - **options** (AuthOptions) - Required - Configuration object for the middleware. ### Returns - Express middleware function. ``` -------------------------------- ### Restrict access with claimEquals Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use the `claimEquals` middleware to restrict access based on a claim matching a specific value. It checks that the claim exists and matches the expected value, raising a 401 `invalid_token` error if it does not. ```javascript const { auth, claimEquals } = require('express-oauth2-jwt-bearer'); // Initialise the auth middleware with environment variables and restrict // access to your api to users with a valid Access Token JWT app.use(auth()); // Restrict access to the admin api to users with the `isAdmin: true` claim app.get('/api/admin', claimEquals('isAdmin', true), (req, res, next) => { // ... }); ``` -------------------------------- ### Require certificate-bound tokens with mtls.required: true Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Configure the auth middleware to require every token to be certificate-bound. Set mtls.enabled and mtls.required to true, and provide a getCertificate callback that extracts the client certificate from the request header. With required: true, the SDK returns 400 invalid_request when a cert-bound token arrives without a certificate, and 401 invalid_token when the thumbprint mismatches or the token has no binding. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', getCertificate: (req) => { const pem = req.headers['client-certificate']; return typeof pem === 'string' ? decodeURIComponent(pem) : undefined; }, mtls: { enabled: true, required: true, // Reject tokens with no cnf.x5t#S256 binding }, }) ); app.get('/api/secure-resource', (req, res) => { res.send('Certificate-bound token validated'); }); ``` -------------------------------- ### scopeIncludesAny Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/index.html Middleware for checking if any of the specified scopes are present. ```APIDOC ## scopeIncludesAny ### Description Creates a middleware function that checks if the JWT payload contains at least one of the specified scopes. ### Usage ```javascript const { scopeIncludesAny } = require('express-oauth2-jwt-bearer'); app.use(scopeIncludesAny('read:data', 'write:data')); ``` ### Parameters - **...scopes** (string[]) - Required - The list of scopes to check. ### Returns - Express middleware function. ``` -------------------------------- ### Accept both cert-bound and regular Bearer tokens Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Enable mTLS validation with mtls.enabled true (default) and mtls.required false (default) to accept both certificate-bound and regular Bearer tokens. Non-bound tokens pass through as regular Bearer tokens. ```javascript const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', getCertificate: (req) => { const pem = req.headers['client-certificate']; return typeof pem === 'string' ? decodeURIComponent(pem) : undefined; }, mtls: { enabled: true, // Validate cnf.x5t#S256 when present (default) required: false, // Non-bound tokens are still accepted (default) }, }) ); app.get('/api/resource', (req, res) => { res.send('Access granted'); }); ``` -------------------------------- ### Return DER bytes from getCertificate Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Return the raw DER bytes of the peer certificate when the Node process terminates TLS directly (no proxy). This is an alternative to reading a header. ```javascript getCertificate: (req) => req.socket.getPeerCertificate()?.raw || undefined; ``` -------------------------------- ### claimIncludes Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/index.html Middleware for checking if a claim includes a specific value. ```APIDOC ## claimIncludes ### Description Creates a middleware function that checks if a specific claim in the JWT payload includes a given value. The claim must be an array or a string. ### Usage ```javascript const { claimIncludes } = require('express-oauth2-jwt-bearer'); app.use(claimIncludes('permissions', 'read:data')); ``` ### Parameters - **claim** (string) - Required - The name of the claim to check. - **value** (any) - Required - The value to check for inclusion. ### Returns - Express middleware function. ``` -------------------------------- ### Enable Express proxy trust for DPoP htu validation Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Required when the app runs behind a reverse proxy (Nginx, Cloudflare, etc.) so that req.protocol and req.host reflect the original request for DPoP htu construction/validation. ```javascript app.enable('trust proxy'); ``` -------------------------------- ### auth Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/README.md Middleware that will return a 401 if a valid Access token JWT bearer token is not provided in the request. ```APIDOC ## auth ### Description Middleware that will return a 401 if a valid Access token JWT bearer token is not provided in the request. ### Usage Use as Express middleware to protect routes. ### Errors Returns 401 if token is invalid or missing. ``` -------------------------------- ### claimCheck Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/README.md Check the token's claims using a custom method that receives the JWT Payload and should return `true` if the token is valid. Raises a 401 `invalid_token` error if the function returns `false`. ```APIDOC ## claimCheck ### Description Check the token's claims using a custom method that receives the JWT Payload and should return `true` if the token is valid. Raises a 401 `invalid_token` error if the function returns `false`. ### Usage Use as middleware after `auth` to apply custom claim validation. ### Errors Returns 401 `invalid_token` if the custom function returns `false`. ``` -------------------------------- ### Restrict access with requiredScopes Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use the `requiredScopes` middleware to restrict access based on scopes. It raises a 403 `insufficient_scope` error if the `scope` claim does not include all given scopes. ```javascript const { auth, requiredScopes } = require('express-oauth2-jwt-bearer'); // Initialise the auth middleware with environment variables and restrict // access to your api to users with a valid Access Token JWT app.use(auth()); // Restrict access to the messages api to users with the `read:msg` // AND `write:msg` scopes app.get('/api/messages', requiredScopes('read:msg', 'write:msg'), (req, res, next) => { // ... } ); ``` -------------------------------- ### Terminating TLS with nginx proxy Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md nginx configuration to request a client certificate (optional_no_ca) and forward it as a URL-encoded PEM header named 'client-certificate'. The matching getCertificate reads and URL-decodes that header. ```nginx server { listen 443 ssl; server_name api.example.com; ssl_certificate /path/to/server.crt; ssl_certificate_key /path/to/server.key; # Request the client certificate. Use `optional_no_ca` when the certificate # is validated downstream (e.g. by Auth0 at token issuance) rather than by # nginx; use `on` with `ssl_client_certificate` to have nginx verify a CA. ssl_verify_client optional_no_ca; location / { proxy_pass http://127.0.0.1:3000; # $ssl_client_escaped_cert is the URL-encoded PEM of the presented cert. proxy_set_header client-certificate $ssl_client_escaped_cert; } } ``` -------------------------------- ### Require only DPoP tokens Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Enforces stronger protection by requiring DPoP tokens and rejecting Bearer tokens. Set dpop.required to true. ```js const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', dpop: { enabled: true, required: true // Rejects Bearer tokens } }) ); app.get('/api/secure-resource', (req, res) => { res.send('DPoP token validated'); }); ``` -------------------------------- ### claimCheck Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/index.html Middleware for checking custom claims in the JWT payload. ```APIDOC ## claimCheck ### Description Creates a middleware function that checks a custom claim in the JWT payload. The claim must satisfy the provided predicate function. ### Usage ```javascript const { claimCheck } = require('express-oauth2-jwt-bearer'); app.use(claimCheck((payload) => payload.role === 'admin')); ``` ### Parameters - **customClaimCheck** (function) - Required - A function that receives the JWT payload and returns a boolean indicating whether the claim is valid. ### Returns - Express middleware function. ``` -------------------------------- ### JWTPayload Interface Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/JWTPayload.html Defines the recognized JWT Claims Set members. Any other members may also be present. ```APIDOC ## JWTPayload Interface ### Description Represents the recognized JWT Claims Set members. Any other members may also be present. ### Properties #### aud (Optional) - **Type**: string | string[] - **Description**: JWT Audience - **See**: [RFC7519#section-4.1.3](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3) #### exp (Optional) - **Type**: number - **Description**: JWT Expiration Time - **See**: [RFC7519#section-4.1.4](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4) #### iat (Optional) - **Type**: number - **Description**: JWT Issued At - **See**: [RFC7519#section-4.1.6](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6) #### iss (Optional) - **Type**: string - **Description**: JWT Issuer - **See**: [RFC7519#section-4.1.1](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1) #### jti (Optional) - **Type**: string - **Description**: JWT ID - **See**: [RFC7519#section-4.1.7](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7) #### nbf (Optional) - **Type**: number - **Description**: JWT Not Before - **See**: [RFC7519#section-4.1.5](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5) #### sub (Optional) - **Type**: string - **Description**: JWT Subject - **See**: [RFC7519#section-4.1.2](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2) ### Indexable - **propName**: string - unknown ### Source - Defined in node_modules/jose/dist/types/types.d.ts:440 ``` -------------------------------- ### required Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Requires DPoP tokens exclusively when DPoP is enabled. When enabled and required, only DPoP tokens are accepted and non-DPoP tokens are rejected. When DPoP is disabled, setting this flag results in a misconfiguration. ```APIDOC ## required ### Description Requires DPoP tokens exclusively when DPoP is enabled. When `enabled: true` and `required: true`, only DPoP tokens are accepted, and non-DPoP tokens are rejected. When `enabled: false`, setting this flag results in a misconfiguration (Bearer-only mode). ### Default ```ts false ``` ### Example ```ts // DPoP-only: auth({ dpop: { enabled: true, required: true } }) ``` ``` -------------------------------- ### Restrict access with claimIncludes Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use the `claimIncludes` middleware to restrict access based on a claim that includes multiple values. It checks that the claim exists and the expected values are included, raising a 401 `invalid_token` error if not. ```javascript const { auth, claimIncludes } = require('express-oauth2-jwt-bearer'); // Initialise the auth middleware with environment variables and restrict // access to your api to users with a valid Access Token JWT app.use(auth()); // Restrict access to the managers admin api to users with both the role `admin` // AND the role `manager` app.get('/api/admin/managers', claimIncludes('role', 'admin', 'manager'), (req, res, next) => { // ... } ); ``` -------------------------------- ### Restrict access with claimCheck Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Use the `claimCheck` middleware to restrict access based on custom logic. Provide a function that receives the JWT payload and returns `true` if the token is valid; a `false` return raises a 401 `invalid_token` error. ```javascript const { auth, claimCheck } = require('express-oauth2-jwt-bearer'); // Restrict access to the admin edit api to users with the `isAdmin: true` claim // and the `editor` role. app.get('/api/admin/edit', claimCheck(({ isAdmin, roles }) => isAdmin && roles.includes('editor')), (req, res, next) => { // ... } ); ``` -------------------------------- ### Require only Bearer tokens Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/packages/express-oauth2-jwt-bearer/EXAMPLES.md Disables DPoP support explicitly to reject all DPoP tokens and only accept standard Bearer access tokens. ```js const { auth } = require('express-oauth2-jwt-bearer'); app.use( auth({ issuerBaseURL: 'https://YOUR_ISSUER_DOMAIN', audience: 'https://my-api.com', dpop: { enabled: false // DPoP proofs will be ignored } }) ); app.get('/api/bearer-only', (req, res) => { res.send('This route accepts only Bearer tokens'); }); ``` -------------------------------- ### requiredScopes Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/index.html Middleware for checking required scopes in the JWT payload. ```APIDOC ## requiredScopes ### Description Creates a middleware function that checks if the JWT payload contains the required scopes. The scopes are checked against the 'scope' claim. ### Usage ```javascript const { requiredScopes } = require('express-oauth2-jwt-bearer'); app.use(requiredScopes('read:data', 'write:data')); ``` ### Parameters - **...scopes** (string[]) - Required - The list of required scopes. ### Returns - Express middleware function. ``` -------------------------------- ### new UnauthorizedError(message?) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/classes/UnauthorizedError.html Creates a new UnauthorizedError instance. The constructor accepts an optional message string that defaults to 'Unauthorized'. ```APIDOC ## new UnauthorizedError(message?) ### Description Creates a new UnauthorizedError instance. The constructor accepts an optional message string that defaults to 'Unauthorized'. ### Parameters - **message** (string) - Optional - Default: 'Unauthorized' ### Returns - **UnauthorizedError** - A new UnauthorizedError instance. ``` -------------------------------- ### captureStackTrace Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/classes/UnauthorizedError.html Static method inherited from Error that creates a .stack property on a target object. ```APIDOC ## [Static] captureStackTrace ### Description Creates a .stack property on a target object. ### Method Static ### Parameters #### Parameters - **targetObject** (object) - Required - The object on which to create the stack property. - **constructorOpt** (Function) - Optional - Optional constructor function. ### Returns void Inherited from Error.captureStackTrace. ``` -------------------------------- ### new InsufficientScopeError(scopes?, message?) Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/classes/InsufficientScopeError.html Creates a new InsufficientScopeError instance. The error indicates that the request requires higher privileges than provided by the access token. ```APIDOC ## new InsufficientScopeError(scopes?, message?) ### Description Creates a new InsufficientScopeError instance. The error indicates that the request requires higher privileges than provided by the access token. ### Parameters - **scopes** (string[]) - Optional - The required scopes. - **message** (string) - Optional - Default: 'Insufficient Scope' - The error message. ### Returns - **InsufficientScopeError** - The new error instance. ``` -------------------------------- ### Default value for iatLeeway property Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Default value for the `iatLeeway` property of DPoPOptions. Allows 30 seconds of clock skew for future-dated `iat` values. Applied only when `enabled: true` and a DPoP proof is present. ```typescript 30 // 30 seconds ``` -------------------------------- ### Default value for enabled property Source: https://github.com/auth0/node-oauth2-jwt-bearer/blob/main/docs/interfaces/DPoPOptions.html Default value for the `enabled` property of DPoPOptions. When `enabled: true`, requests can use the DPoP authorization scheme and the middleware validates proofs. When `enabled: false`, only the Bearer scheme is supported, DPoP tokens are rejected, and DPoP proof headers are ignored. ```typescript true ```