### HMAC Key Material Example Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/README.md Example of key material for HMAC. It can be a string or a Buffer. ```javascript 'my-secret' or Buffer.from('my-secret') ``` -------------------------------- ### RSA Key Material Example Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/README.md Example of key material for RSA. Requires PEM-encoded private or public key with a minimum 2048-bit modulus. ```javascript fs.readFileSync('private.pem') ``` -------------------------------- ### JWT Signing with SignOptions Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/types.md Example demonstrating how to use the SignOptions object to configure JWT signing parameters. ```javascript const jwt = require('jsonwebtoken'); const options: SignOptions = { algorithm: 'RS256', expiresIn: '2 hours', issuer: 'my-app', audience: 'api-v1', keyid: 'key-2024' }; const token = jwt.sign({ userId: 123 }, privateKey, options); ``` -------------------------------- ### HMAC Symmetric Key Examples Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/configuration.md Examples of symmetric key material for HMAC algorithms. Can be a UTF-8 string or a Buffer. ```javascript 'my-secret-key' ``` ```javascript Buffer.from('my-secret-key') ``` ```javascript createSecretKey(Buffer.from('my-secret-key')) ``` -------------------------------- ### RSA-PSS Public Key Example Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/configuration.md Example of loading an RSA-PSS public key from a PEM-encoded file. Requires Node.js >=6.12.0 or >=8.0.0. ```javascript fs.readFileSync('rsa-pss-public.pem') ``` -------------------------------- ### RSA-PSS Private Key Example Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/configuration.md Example of loading an RSA-PSS private key from a PEM-encoded file. Requires Node.js >=6.12.0 or >=8.0.0. ```javascript fs.readFileSync('rsa-pss-private.pem') ``` -------------------------------- ### RSA Private Key for Signing Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/configuration.md Example of loading an RSA private key from a PEM-encoded file for signing JWTs. ```javascript fs.readFileSync('private.pem') // For signing ``` ```javascript createPrivateKey(fs.readFileSync('private.pem')) ``` -------------------------------- ### Using 'jti' for Token Identification and Revocation Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/claims-reference.md Illustrates how to sign a token with a unique JWT ID ('jti') using the 'jwtid' option and how to verify it. Includes an example of implementing token revocation by checking against a set of revoked JWT IDs. ```javascript const jwt = require('jsonwebtoken'); const { v4: uuid } = require('uuid'); // Sign with unique JWT ID const tokenId = uuid(); jwt.sign({ userId: 123 }, secret, { jwtid: tokenId }); // Verify JWT ID matches expected jwt.verify(token, secret, { jwtid: 'expected-token-id' }); // Token revocation example const revokedTokens = new Set(); function revokeToken(token) { const decoded = jwt.decode(token); revokedTokens.add(decoded.jti); } function verifyAndCheckRevocation(token) { jwt.verify(token, secret, (err, decoded) => { if (err) { console.error('Invalid token:', err); } else if (revokedTokens.has(decoded.jti)) { console.error('Token has been revoked'); } else { console.log('Token is valid'); } }); } ``` -------------------------------- ### RSA Public Key for Verification Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/configuration.md Example of loading an RSA public key from a PEM-encoded file for verifying JWTs. ```javascript fs.readFileSync('public.pem') // For verification ``` ```javascript createPublicKey(fs.readFileSync('public.pem')) ``` -------------------------------- ### Time Format Examples for jsonwebtoken Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/README.md Examples of time formats supported by the jsonwebtoken library, which uses the 'ms' library for parsing. Use explicit units like '120s' for seconds, not just numbers. ```javascript '100' // 100 milliseconds '1s' // 1 second '10m' // 10 minutes '1h' // 1 hour '1d' // 1 day '7d' // 7 days '2w' // 2 weeks '1y' // 1 year '1h 30m' // Combined format ``` -------------------------------- ### JWT Verification with Custom Options Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how to use the VerifyOptions object to configure JWT verification. This example specifies allowed algorithms, audience patterns, multiple issuers, clock tolerance, and maximum token age. ```javascript const jwt = require('jsonwebtoken'); const options = { algorithms: ['RS256'], audience: [/api-v\d+/, 'admin-api'], issuer: ['auth-server', 'legacy-auth'], clockTolerance: 10, maxAge: '24 hours' }; jwt.verify(token, publicKey, options, (err, decoded) => { if (!err) console.log('Verified:', decoded); }); ``` -------------------------------- ### ECDSA Private Key for Signing Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/configuration.md Example of loading an ECDSA private key from a PEM-encoded file for signing JWTs. ```javascript fs.readFileSync('ec-private.pem') // For signing ``` ```javascript createPrivateKey(fs.readFileSync('ec-private.pem')) ``` -------------------------------- ### Verify JWT tokens using node-jsonwebtoken Source: https://github.com/auth0/node-jsonwebtoken/blob/master/README.md Examples demonstrating synchronous and asynchronous verification of symmetric and asymmetric tokens, including error handling and claim validation. ```javascript // verify a token symmetric - synchronous var decoded = jwt.verify(token, 'shhhhh'); console.log(decoded.foo) // bar // verify a token symmetric jwt.verify(token, 'shhhhh', function(err, decoded) { console.log(decoded.foo) // bar }); // invalid token - synchronous try { var decoded = jwt.verify(token, 'wrong-secret'); } catch(err) { // err } // invalid token jwt.verify(token, 'wrong-secret', function(err, decoded) { // err // decoded undefined }); // verify a token asymmetric var cert = fs.readFileSync('public.pem'); // get public key jwt.verify(token, cert, function(err, decoded) { console.log(decoded.foo) // bar }); // verify audience var cert = fs.readFileSync('public.pem'); // get public key jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) { // if audience mismatch, err == invalid audience }); // verify issuer var cert = fs.readFileSync('public.pem'); // get public key jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) { // if issuer mismatch, err == invalid issuer }); // verify jwt id var cert = fs.readFileSync('public.pem'); // get public key ``` -------------------------------- ### ECDSA Public Key for Verification Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/configuration.md Example of loading an ECDSA public key from a PEM-encoded file for verifying JWTs. ```javascript fs.readFileSync('ec-public.pem') // For verification ``` ```javascript createPublicKey(fs.readFileSync('ec-public.pem')) ``` -------------------------------- ### ECDSA Key Material Example Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/README.md Example of key material for ECDSA. Requires PEM-encoded private or public key for P-256, P-384, or P-521 curves. ```javascript fs.readFileSync('ec-private.pem') ``` -------------------------------- ### Production JWT Signing and Verification with RS256 Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/INDEX.md This example shows a production-ready scenario for signing and verifying JWTs using RS256. It includes setting claims like expiration, issuer, and audience during signing, and performing corresponding validations during verification. Asymmetric keys are loaded from files. ```javascript const jwt = require('jsonwebtoken'); const fs = require('fs'); const privateKey = fs.readFileSync('private.pem'); const publicKey = fs.readFileSync('public.pem'); // Sign with claims const token = jwt.sign({ userId: 123 }, privateKey, { algorithm: 'RS256', expiresIn: '24 hours', issuer: 'auth-server', audience: 'my-api' }); // Verify with validation jwt.verify(token, publicKey, { algorithms: ['RS256'], issuer: 'auth-server', audience: 'my-api', clockTolerance: 10 }, (err, decoded) => { if (!err) console.log('Valid token, user:', decoded.userId); }); ``` -------------------------------- ### NotBeforeError Usage Example (Async) Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/errors.md Demonstrates how to catch and handle a NotBeforeError when verifying a JWT asynchronously. It checks if the error is an instance of NotBeforeError and logs the activation date. ```javascript const jwt = require('jsonwebtoken'); jwt.verify(token, 'secret', (err, decoded) => { if (err) { if (err instanceof jwt.NotBeforeError) { console.log('Token becomes active at:', err.date); // Retry verification later } else { console.error('Verification failed:', err.message); } } }); ``` -------------------------------- ### Algorithm Inference with RSA Public Key Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/algorithms-reference.md When verifying a token with an RSA public key, the library defaults to RS256, RS384, and RS512 algorithms if none are explicitly provided. This example assumes the token is signed with one of these algorithms. ```javascript const jwt = require('jsonwebtoken'); const fs = require('fs'); // With RSA public key, algorithms default to RS256/RS384/RS512 const publicKey = fs.readFileSync('public.pem'); jwt.verify(token, publicKey, (err, decoded) => { // algorithms: ['RS256', 'RS384', 'RS512'] }); ``` -------------------------------- ### NotBeforeError Usage Example (Sync) Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/errors.md Shows how to handle a NotBeforeError when verifying a JWT synchronously using a try-catch block. It checks the error name and logs the activation date if it's a NotBeforeError. ```javascript try { const decoded = jwt.verify(token, 'secret'); } catch (err) { if (err.name === 'NotBeforeError') { console.log('Token not yet valid. Becomes valid at:', err.date); } } ``` -------------------------------- ### Sign and Verify JWT with ES256 Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/algorithms-reference.md Example of signing a JWT using a private key with the ES256 algorithm and verifying it with the corresponding public key. The library automatically validates curve matching. ```javascript const jwt = require('jsonwebtoken'); const fs = require('fs'); const privateKey = fs.readFileSync('private.pem'); // P-256 key const publicKey = fs.readFileSync('public.pem'); // Sign with ES256 const token = jwt.sign({ userId: 123 }, privateKey, { algorithm: 'ES256' }); // Verify with ES256 const decoded = jwt.verify(token, publicKey, { algorithms: ['ES256'] }); ``` -------------------------------- ### Algorithm Inference with HMAC Secret Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/algorithms-reference.md When verifying a token with an HMAC secret, the library defaults to HS256, HS384, and HS512 algorithms if none are explicitly provided. This example assumes the token is signed with one of these algorithms. ```javascript const jwt = require('jsonwebtoken'); // With HMAC secret, algorithms default to HS256/HS384/HS512 jwt.verify(token, 'secret', (err, decoded) => { // algorithms: ['HS256', 'HS384', 'HS512'] }); ``` -------------------------------- ### Time Format Examples Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/quick-reference.md Strings representing durations are parsed by the 'ms' library. Numeric strings default to milliseconds; use 's' suffix for seconds. ```javascript '100' // 100 milliseconds ``` ```javascript '1s' // 1 second ``` ```javascript '10m' // 10 minutes ``` ```javascript '1h' // 1 hour ``` ```javascript '1d' // 1 day ``` ```javascript '7d' // 7 days ``` ```javascript '2w' // 2 weeks ``` ```javascript '1y' // 1 year ``` ```javascript '1h 30m' // 1 hour 30 minutes ``` ```javascript '2 days 3 hours' // 2 days 3 hours ``` -------------------------------- ### Getting Complete Token Structure (Header, Payload, Signature) Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/verify.md Verify a JWT and retrieve its complete structure, including the header, payload, and signature. This is useful for inspecting token components. ```javascript const jwt = require('jsonwebtoken'); const token = 'eyJ...'; const decoded = jwt.verify(token, 'secret', { complete: true }); console.log('Header:', decoded.header); console.log('Payload:', decoded.payload); console.log('Signature:', decoded.signature); ``` -------------------------------- ### package.json Main Entry Point Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/module-exports.md Defines the main file to be loaded when the package is required. Node.js resolves the package and loads the file specified in the 'main' field. ```json { "main": "index.js", "files": ["lib", "decode.js", "sign.js", "verify.js"] } ``` -------------------------------- ### Setting and Verifying 'nbf' Claim Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/claims-reference.md Demonstrates how to set the 'nbf' claim using the 'notBefore' option or directly in the payload. It also shows how to verify the token with default 'nbf' checks, skipping the check, and using clock tolerance. ```javascript const jwt = require('jsonwebtoken'); // Set not-before via notBefore option (recommended) jwt.sign({ userId: 123 }, secret, { notBefore: '1 hour' // Token valid 1 hour from now }); // Creates nbf claim: current_time + 3600 // Set not-before directly jwt.sign({ userId: 123, nbf: Math.floor(Date.now() / 1000) + 3600 }, secret); // Verify with not-before check (default) jwt.verify(token, secret, (err, decoded) => { if (err instanceof jwt.NotBeforeError) { console.log('Token becomes valid at:', err.date); } }); // Skip not-before check jwt.verify(token, secret, { ignoreNotBefore: true }); // Custom clock tolerance (5 seconds) jwt.verify(token, secret, { clockTolerance: 5 }); ``` -------------------------------- ### CommonJS Import and Usage Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/module-exports.md Demonstrates how to import and use the main jsonwebtoken functions and error classes using CommonJS `require`. ```javascript const jwt = require('jsonwebtoken'); // Use exported functions const token = jwt.sign(payload, secret); const decoded = jwt.verify(token, secret); const unverified = jwt.decode(token); // Use error classes for instanceof checks if (err instanceof jwt.JsonWebTokenError) { ... } if (err instanceof jwt.TokenExpiredError) { ... } if (err instanceof jwt.NotBeforeError) { ... } ``` -------------------------------- ### ECDSA Curve Validation Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/algorithms-reference.md Validates that the curve in the ECDSA key matches the algorithm used for signing. For example, an ES256 algorithm requires a P-256 key. ```javascript const jwt = require('jsonwebtoken'); const fs = require('fs'); // P-256 key const p256Key = fs.readFileSync('p256-private.pem'); jwt.sign(payload, p256Key, { algorithm: 'ES256' }); // OK (P-256 matches) jwt.sign(payload, p256Key, { algorithm: 'ES384' }); // Error (P-256 doesn't match P-384) ``` -------------------------------- ### RSA-PSS Parameters Validation Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/algorithms-reference.md Validates RSA-PSS key parameters, specifically the hash algorithm used. For example, PS256 algorithm expects an RSA-PSS key with SHA-256. ```javascript const jwt = require('jsonwebtoken'); // RSA-PSS key with SHA-256 jwt.sign(payload, ps256Key, { algorithm: 'PS256' }); // OK // RSA-PSS key with wrong hash algorithm: Error jwt.sign(payload, ps384Key, { algorithm: 'PS256' }); // Error ``` -------------------------------- ### Express JWT Authentication Middleware Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/module-exports.md An example of an Express middleware function to authenticate incoming requests using JWTs. It extracts the token from the Authorization header and verifies it. ```javascript const jwt = require('jsonwebtoken'); function authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) { return res.sendStatus(401); } jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => { if (err instanceof jwt.TokenExpiredError) { return res.status(401).json({ error: 'Token expired' }); } else if (err instanceof jwt.JsonWebTokenError) { return res.status(403).json({ error: 'Invalid token' }); } req.user = decoded; next(); }); } app.use(authenticateToken); ``` -------------------------------- ### RSA Signing and Verification Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/quick-reference.md Shows how to sign a JWT using an RSA private key and verify it with an RSA public key. Requires reading keys from files. ```javascript const fs = require('fs'); const privateKey = fs.readFileSync('private.pem'); const publicKey = fs.readFileSync('public.pem'); // Signing jwt.sign(payload, privateKey, { algorithm: 'RS256' }); // Verification jwt.verify(token, publicKey, { algorithms: ['RS256'] }); ``` -------------------------------- ### Accessing JWT Claims with the 'complete' Option Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/claims-reference.md Demonstrates how to use the 'complete: true' option with jwt.decode() to access the JWT payload, header, and signature. ```javascript const jwt = require('jsonwebtoken'); const decoded = jwt.decode(token, { complete: true }); console.log(decoded.payload.exp); console.log(decoded.payload.iss); ``` -------------------------------- ### Sign and Verify JWT with Standard Claims Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how to sign a JWT with standard claims such as issuer, subject, audience, jwtid, and expiresIn, and then how to verify the token using the same claims. Ensure the secret key matches for verification. ```javascript const jwt = require('jsonwebtoken'); // Signing with standard claims const token = jwt.sign( { userId: 123 }, 'secret', { issuer: 'auth-server', subject: 'user-123', audience: 'my-app', jwtid: 'token-uuid-1234', expiresIn: '1h' } ); // Verifying with standard claims jwt.verify(token, 'secret', { issuer: 'auth-server', subject: 'user-123', audience: 'my-app', jwtid: 'token-uuid-1234' }, (err, decoded) => { if (!err) console.log('All claims validated:', decoded); }); ``` -------------------------------- ### DecodeOptions Interface Definition Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/types.md Defines the configuration options for the jwt.decode() function. Use json to force JSON parsing and complete to get header, payload, and signature. ```typescript interface DecodeOptions { json?: boolean complete?: boolean } ``` -------------------------------- ### Sign and Verify JWT Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/module-exports.md Demonstrates how to sign a JWT with a payload and secret, and then verify it. Includes basic error handling for expired or invalid tokens. ```javascript const jwt = require('jsonwebtoken'); // Sign a token const token = jwt.sign({ userId: 123 }, 'secret', { expiresIn: '1h' }); // Verify a token jwt.verify(token, 'secret', (err, decoded) => { if (err instanceof jwt.TokenExpiredError) { console.error('Token expired'); } else if (err) { console.error('Invalid token'); } else { console.log('User:', decoded.userId); } }); ``` -------------------------------- ### Asynchronous RSA Signing (RS256) Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/sign.md Use this for asynchronous signing with RSA, typically for more secure applications. Requires reading a private key file. ```javascript const jwt = require('jsonwebtoken'); const fs = require('fs'); const privateKey = fs.readFileSync('private.pem'); const payload = { userId: 123, role: 'admin' }; jwt.sign(payload, privateKey, { algorithm: 'RS256' }, (err, token) => { if (err) { console.error('Signing failed:', err); } else { console.log('Token:', token); } }); ``` -------------------------------- ### HMAC Signing with Default and Other Algorithms Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/quick-reference.md Demonstrates signing a JWT using the default HS256 algorithm and other supported HMAC algorithms like HS384 and HS512. ```javascript // Default HS256 jwt.sign(payload, sharedSecret); // Other HMAC algorithms jwt.sign(payload, sharedSecret, { algorithm: 'HS384' }); jwt.sign(payload, sharedSecret, { algorithm: 'HS512' }); ``` -------------------------------- ### Asymmetric Key and Algorithm Mapping Source: https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9 Reference table for mapping asymmetric key types to their supported JWS algorithms. ```APIDOC ## Asymmetric Key and Algorithm Mapping ### Description Defines the required key types for specific JWS algorithms supported by the library. ### Supported Mappings | Asymmetric Key Type | Algorithms | | --- | --- | | ec | ES256, ES384, ES512 | | rsa | RS256, PS256, RS384, PS384, RS512, PS512 | | rsa-pss | PS256, PS384, PS512 | ### Configuration - **allowInvalidAsymmetricKeyTypes** (boolean) - Optional - Set to true to preserve old behavior regarding asymmetric key type validation. ``` -------------------------------- ### Correctly Signing JWTs with Time Claims Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/claims-reference.md Demonstrates the correct way to use Unix timestamps in seconds for 'exp', 'nbf', and 'iat' claims when signing JWTs. Avoids common errors with JavaScript's millisecond timestamps. ```javascript const jwt = require('jsonwebtoken'); // Correct: Unix timestamp in seconds const now = Math.floor(Date.now() / 1000); jwt.sign({ exp: now + 3600, // 1 hour from now nbf: now, iat: now }, secret); // Wrong: JavaScript timestamp in milliseconds jwt.sign({ exp: Date.now() + 3600000, // This is 3600000 seconds from now (not 1 hour!) iat: Date.now() }, secret); // Correct way to add milliseconds jwt.sign({ exp: Math.floor(Date.now() / 1000) + 3600, // Convert to seconds, then add seconds iat: Math.floor(Date.now() / 1000) }, secret); ``` -------------------------------- ### Setting and Verifying Token Expiration Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/quick-reference.md Shows how to set expiration times for JWTs using various formats (e.g., '1h', 3600 seconds, '7d') and how to verify tokens with clock tolerance. ```javascript // Expires in 1 hour jwt.sign(payload, secret, { expiresIn: '1h' }); // Expires in 3600 seconds jwt.sign(payload, secret, { expiresIn: 3600 }); // Expires in 7 days jwt.sign(payload, secret, { expiresIn: '7d' }); // Verify with tolerance jwt.verify(token, secret, { clockTolerance: 10 }); ``` -------------------------------- ### jsonwebtoken Node.js Project File Structure Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/INDEX.md This snippet displays the directory structure of the jsonwebtoken Node.js project. It outlines the main files and their purposes, aiding in understanding the library's organization. ```bash /workspace/home/output/ ├── INDEX.md (this file) ├── sign.md API reference for jwt.sign() ├── verify.md API reference for jwt.verify() ├── decode.md API reference for jwt.decode() ├── errors.md Error classes and handling ├── types.md Type interfaces ├── configuration.md Configuration options ├── algorithms-reference.md Algorithm guide ├── claims-reference.md JWT claims guide ├── module-exports.md Module structure └── quick-reference.md Quick lookup guide ``` -------------------------------- ### Sign a JWT Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/MANIFEST.txt Use the `sign` function to create a JSON Web Token. It takes a payload, a secret or private key, and optional options or a callback. ```javascript const jwt = require('jsonwebtoken'); // Sign a payload with a secret const token = jwt.sign({ foo: 'bar' }, 'secret'); // Sign a payload with a secret and options const tokenWithOptions = jwt.sign({ foo: 'bar' }, 'secret', { expiresIn: '1h', algorithm: 'HS256' }); // Sign with a callback jwt.sign({ foo: 'bar' }, 'secret', (err, token) => { if (err) { console.error('Error signing token:', err); } else { console.log('Signed token:', token); } }); // Sign with private key (RS256) const privateKey = require('fs').readFileSync('private.key'); const tokenRS256 = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }); ``` -------------------------------- ### Verify JWT using getKey callback Source: https://github.com/auth0/node-jsonwebtoken/blob/master/README.md Use a callback function to dynamically retrieve the signing key, often used with JWKS providers. ```javascript // Verify using getKey callback // Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys. var jwksClient = require('jwks-rsa'); var client = jwksClient({ jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json' }); function getKey(header, callback){ client.getSigningKey(header.kid, function(err, key) { var signingKey = key.publicKey || key.rsaPublicKey; callback(null, signingKey); }); } jwt.verify(token, getKey, options, function(err, decoded) { console.log(decoded.foo) // bar }); ``` -------------------------------- ### Setting and Verifying Subject and JWT ID Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/quick-reference.md Demonstrates how to include subject and JWT ID (jti) claims when signing a JWT and how to verify them during token validation. ```javascript // Sign with subject and jwt id jwt.sign(payload, secret, { subject: 'user-123', jwtid: 'token-uuid' }); // Verify subject and jwt id jwt.verify(token, secret, { subject: 'user-123', jwtid: 'token-uuid' }); ``` -------------------------------- ### Setting and Verifying Issuer and Audience Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/quick-reference.md Illustrates how to sign a JWT with specific issuer and audience claims, and how to verify these claims during token validation. Supports string, regex, and array for audience. ```javascript // Sign with issuer and audience jwt.sign(payload, secret, { issuer: 'auth-server', audience: 'my-app' }); // Verify issuer and audience jwt.verify(token, secret, { issuer: 'auth-server', audience: 'my-app' }); // Audience with regex jwt.verify(token, secret, { audience: /api-v\d+/ }); // Multiple audiences jwt.verify(token, secret, { audience: ['app1', 'app2', /service-\w+/] }); ``` -------------------------------- ### jwt.sign - Payload Options Source: https://github.com/auth0/node-jsonwebtoken/blob/master/README.md Demonstrates setting expiration and backdating JWTs using payload claims or options. ```APIDOC ## jwt.sign with Expiration and Backdating ### Description Shows how to set expiration times and backdate JWTs using `expiresIn` option or `exp` claim, and `iat` claim for backdating. ### Method POST (conceptual, as this is a library function) ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **payload** (object) - The data to encode. Can include `exp`, `iat` claims. - **secretOrPrivateKey** (string) - The secret key. - **options** (object) - Optional signing options, including `expiresIn`. ### Request Example (Expiration using `expiresIn`) ```js jwt.sign({ data: 'foobar' }, 'secret', { expiresIn: '1h' }); ``` ### Request Example (Expiration using `exp` claim) ```js jwt.sign({ exp: Math.floor(Date.now() / 1000) + (60 * 60), data: 'foobar' }, 'secret'); ``` ### Request Example (Backdating using `iat`) ```js var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh'); ``` ### Response #### Success Response (200) - **token** (string) - The generated JSON Web Token with appropriate claims. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vYmFyIiwiaWF0IjoxNDk1NjY0NzQ3LCJleHAiOjE0OTU2NjgzNDd9.example_signature" } ``` ``` -------------------------------- ### Setting and Verifying 'iat' Claim Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/claims-reference.md Shows how the 'iat' claim is automatically set to the current time and how to disable it using 'noTimestamp'. It also covers using an existing 'iat' and validating token age with 'maxAge'. ```javascript const jwt = require('jsonwebtoken'); // iat automatically set to current time const token = jwt.sign({ userId: 123 }, secret); // Creates iat claim: current_time // Disable automatic iat jwt.sign({ userId: 123 }, secret, { noTimestamp: true }); // No iat claim // Use existing iat (not replaced with current time) jwt.sign({ userId: 123, iat: Math.floor(Date.now() / 1000) - 3600 // Backdate by 1 hour }, secret); // Uses the provided iat value // Validate token age via maxAge jwt.verify(token, secret, { maxAge: '24 hours' // Token must be less than 24 hours old }); // maxAge checks: current_time - iat must be less than maxAge ``` -------------------------------- ### Sign and Verify JWT with 'none' Algorithm Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/algorithms-reference.md Use the 'none' algorithm for unsigned tokens. This is suitable for testing or non-sensitive data as it offers no cryptographic security. Ensure to specify ['none'] in the verify options. ```javascript const jwt = require('jsonwebtoken'); // Sign without signature const token = jwt.sign({ debug: 'info' }, '', { algorithm: 'none' }); // Result: eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkZWJ1ZyI6ImluZm8ifQ. // Verify unsigned token const decoded = jwt.verify(token, '', { algorithms: ['none'] }); ``` -------------------------------- ### Verify JWT using Dynamic Key Selection (JWKS) Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/quick-reference.md Verify a JWT by dynamically fetching the public key from a JWKS endpoint. This involves using `jwks-rsa` to manage the JWKS client and retrieve the correct signing key based on the token's header. ```javascript const jwksClient = require('jwks-rsa'); const client = jwksClient({ jwksUri: 'https://auth-server.com/.well-known/jwks.json' }); function getKey(header, callback) { client.getSigningKey(header.kid, (err, key) => { if (err) callback(err); else callback(null, key.publicKey); }); } jwt.verify(token, getKey, { algorithms: ['RS256'] }, (err, decoded) => { if (!err) console.log('Token verified'); }); ``` -------------------------------- ### Generate RSA Private and Public Keys Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/quick-reference.md Use OpenSSL to generate an RSA private key and then derive the corresponding public key. ```bash # Private key openssl genrsa -out private.pem 2048 ``` ```bash # Public key from private openssl rsa -in private.pem -pubout -out public.pem ``` -------------------------------- ### Sign and Verify JWT with Expiration Time Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/claims-reference.md Demonstrates setting and verifying the 'exp' (Expiration Time) claim. It's recommended to use the 'expiresIn' option for setting expiration, which is automatically validated by jwt.verify() unless 'ignoreExpiration' is true. Includes handling 'TokenExpiredError' and custom 'clockTolerance'. ```javascript const jwt = require('jsonwebtoken'); // Set expiration via expiresIn (recommended) jwt.sign({ userId: 123 }, secret, { expiresIn: '1 hour' }); // Creates exp claim: current_time + 3600 // Set expiration directly (not recommended with expiresIn) jwt.sign({ userId: 123, exp: Math.floor(Date.now() / 1000) + 3600 }, secret); // Verify with expiration check (default) jwt.verify(token, secret, (err, decoded) => { if (err instanceof jwt.TokenExpiredError) { console.log('Token expired at:', err.expiredAt); } }); // Skip expiration check jwt.verify(token, secret, { ignoreExpiration: true }); // Custom clock tolerance (10 seconds) jwt.verify(token, secret, { clockTolerance: 10 }); ``` -------------------------------- ### SignOptions Interface Definition Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/types.md Defines the structure for configuration options when signing a JWT. ```typescript interface SignOptions { algorithm?: string expiresIn?: number | string notBefore?: number | string audience?: string | string[] issuer?: string subject?: string jwtid?: string noTimestamp?: boolean header?: Record keyid?: string mutatePayload?: boolean allowInsecureKeySizes?: boolean allowInvalidAsymmetricKeyTypes?: boolean encoding?: string } ``` -------------------------------- ### Sign and Verify with HS256 HMAC Algorithm Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/algorithms-reference.md Demonstrates how to sign a JWT using the HS256 HMAC algorithm and subsequently verify it using the same shared secret. Ensure the secret is kept confidential as it's used for both operations. ```javascript const jwt = require('jsonwebtoken'); const secret = 'my-shared-secret-key'; // Sign const token = jwt.sign({ userId: 123 }, secret, { algorithm: 'HS256' }); // Verify (same secret) const decoded = jwt.verify(token, secret, { algorithms: ['HS256'] }); ``` -------------------------------- ### Accessing JWT Claims via jwt.decode() Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/claims-reference.md Shows how to decode a JWT and access standard claims like 'exp', 'nbf', 'iat', 'iss', 'sub', 'aud', and 'jti' using the jwt.decode() method. ```javascript const jwt = require('jsonwebtoken'); const decoded = jwt.decode(token); console.log(decoded.exp); // Expiration time console.log(decoded.nbf); // Not before time console.log(decoded.iat); // Issued at time console.log(decoded.iss); // Issuer console.log(decoded.sub); // Subject console.log(decoded.aud); // Audience console.log(decoded.jti); // JWT ID ``` -------------------------------- ### Verify Unsigned Tokens with 'none' Algorithm Source: https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9 To verify unsigned tokens, explicitly provide 'none' in the options.algorithms array. This change was introduced to enhance security by preventing accidental verification of unsigned tokens. ```javascript const decoded = jwt.verify(unsigned, undefined, { algorithms: ['none'] }); ``` -------------------------------- ### Minimal JWT Signing and Verification Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/INDEX.md This snippet demonstrates the most basic usage of the jsonwebtoken library for signing a payload into a token and then verifying it. It uses the default HS256 algorithm. ```javascript const jwt = require('jsonwebtoken'); // Sign (default HS256) const token = jwt.sign({ userId: 123 }, 'secret'); // Verify const decoded = jwt.verify(token, 'secret'); ``` -------------------------------- ### Accessing JWT Claims via jwt.verify() Callback Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/claims-reference.md Illustrates how to access claims, including custom ones, within the callback function of jwt.verify() after successful token verification. ```javascript const jwt = require('jsonwebtoken'); jwt.verify(token, secret, (err, decoded) => { if (!err) { console.log(decoded.exp); console.log(decoded.userId); // Custom claim } }); ``` -------------------------------- ### Generate ECDSA Keys with OpenSSL Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/algorithms-reference.md Use OpenSSL to generate private and public keys for ES256, ES384, and ES512 algorithms. Ensure you use the correct curve name for each algorithm. ```bash # P-256 for ES256 openssl ecparam -name prime256v1 -genkey -noout -out private.pem openssl ec -in private.pem -pubout -out public.pem # P-384 for ES384 openssl ecparam -name secp384r1 -genkey -noout -out private.pem # P-521 for ES512 openssl ecparam -name secp521r1 -genkey -noout -out private.pem ``` -------------------------------- ### Accessing DecodedToken Components Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how to access the header, payload, and signature from a token decoded with the 'complete: true' option. Useful for verifying specific claims or token integrity. ```javascript const jwt = require('jsonwebtoken'); const decoded = jwt.decode(token, { complete: true }); const keyId = decoded.header.kid; const userId = decoded.payload.userId; const signature = decoded.signature; ``` -------------------------------- ### Module Exports Structure Source: https://github.com/auth0/node-jsonwebtoken/blob/master/_autodocs/module-exports.md This snippet shows the structure of the main module exports for the jsonwebtoken library. ```javascript module.exports = { decode: require('./decode'), verify: require('./verify'), sign: require('./sign'), JsonWebTokenError: require('./lib/JsonWebTokenError'), NotBeforeError: require('./lib/NotBeforeError'), TokenExpiredError: require('./lib/TokenExpiredError'), }; ``` -------------------------------- ### jwt.verify(token, secretOrPublicKey, [options, callback]) Source: https://github.com/auth0/node-jsonwebtoken/blob/master/README.md Verifies the signature and claims of a JWT. Supports static keys or dynamic key retrieval via a callback. ```APIDOC ## jwt.verify(token, secretOrPublicKey, [options, callback]) ### Description Verifies the signature and claims of a JWT. If the token is invalid or claims do not match, an error is returned in the callback. ### Parameters #### Path Parameters - **token** (string) - Required - The JWT string to verify. - **secretOrPublicKey** (string|Buffer|Function) - Required - The secret or public key to verify the signature. Can be a function (getKey) for dynamic retrieval. #### Request Body - **options** (object) - Optional - Configuration object containing: - **audience** (string) - Expected audience claim. - **issuer** (string) - Expected issuer claim. - **jwtid** (string) - Expected JWT ID claim. - **subject** (string) - Expected subject claim. - **algorithms** (array) - List of allowed algorithms. ### Response #### Success Response (200) - **decoded** (object) - The decoded payload of the JWT. #### Error Handling - **TokenExpiredError** - Thrown if the token is expired. - **JsonWebTokenError** - Thrown for invalid signatures, malformed tokens, or claim mismatches (audience, issuer, etc.). - **NotBeforeError** - Thrown if the current time is before the nbf claim. ```