
Security News
Socket Integrates With Bun 1.3’s Security Scanner API
Socket now integrates with Bun 1.3’s Security Scanner API to block risky packages at install time and enforce your organization’s policies in local dev and CI.
jwt-validate
Advanced tools
Easily validate JWT tokens in Node.js. This package builds on top of the jsonwebtoken and jwks-rsa packages and extends their functionality with several convenience features, including:
npm install jwt-validate
Following snippets show the basic setup for validating JWT tokens in apps that use the CommonJS and ESM module systems. The following sections show specific use cases on top of the basic setup.
const { TokenValidator, getEntraJwksUri } = require('jwt-validate');
// gets the JWKS URL for the Microsoft Entra common tenant
const entraJwksUri = await getEntraJwksUri();
// create a new token validator with the JWKS URL
const validator = new TokenValidator({
jwksUri: entraJwksUri
});
try {
// define validation options
const options = {
// ...
};
// validate the token
const validToken = await validator.validateToken(token, options);
// Token is valid
}
catch (ex) {
// Token is invalid
console.error(ex);
}
import { TokenValidator, getEntraJwksUri } from 'jwt-validate';
// gets the JWKS URL for the Microsoft Entra common tenant
const entraJwksUri = await getEntraJwksUri();
// create a new token validator with the JWKS URL
const validator = new TokenValidator({
jwksUri: entraJwksUri
});
try {
// define validation options
const options = {
// ...
};
// validate the token
const validToken = await validator.validateToken(token, options);
// Token is valid
}
catch (ex) {
// Token is invalid
console.error(ex);
}
Following are several examples of using the package to validate JWT tokens in different scenarios. For the basic setup see the previous section.
const options = {
// allowed audience
audience: 'cda00000-0000-0000-0000-a00000000001',
// allowed issuer
issuer: 'https://login.microsoftonline.com/cda00000-0000-0000-0000-700000000001/v2.0'
};
// validate the token
const validToken = await validator.validateToken(token, options);
Validate that the token is an application token by checking the idtyp
claim. Requires the idtyp
claim to be present in the token.
const options = {
idtyp: 'app'
};
// validate the token
const validToken = await validator.validateToken(token, options);
// Token is valid
const options = {
ver: '2.0'
};
// validate the token
const validToken = await validator.validateToken(token, options);
const options = {
// list of allowed tenants
allowedTenants: ['cda00000-0000-0000-0000-700000000001'],
// allowed audience
audience: 'cda00000-0000-0000-0000-a00000000001',
// allowed issuer multitenant
issuer: 'https://login.microsoftonline.com/{tenantid}/v2.0'
};
// validate the token
const validToken = await validator.validateToken(token, options);
Validate that the token has one of the specified roles or scopes. This is a common requirements for APIs that support delegated and application permissions and allow usage with several scopes.
const options = {
scp: ['Customers.Read', 'Customers.ReadWrite'],
roles: ['Customers.Read.All', 'Customers.ReadWrite.All']
};
// validate the token
const validToken = await validator.validateToken(token, options);
const { TokenValidator, getEntraJwksUri, CloudType } = require('jwt-validate');
// gets the JWKS URL for the Microsoft Entra common tenant in the US Government cloud
const entraJwksUri = await getEntraJwksUri('cda00000-0000-0000-0000-700000000002', CloudType.USGovernment);
// create a new token validator with the JWKS URL
const validator = new TokenValidator({
jwksUri: entraJwksUri
});
TokenValidator
Responsible for validating JWT tokens using JWKS (JSON Web Key Set).
constructor(options)
options
: Object - Configuration options for the TokenValidator.
cache
: boolean (optional, default=true
) - Whether to cache the JWKS keys.cacheMaxAge
: number (optional, default=86400000
) - The maximum age of the cache in milliseconds (default is 24 hours).jwksUri
: string - The URI to fetch the JWKS keys from.Error
- If the options parameter is not provided.async validateToken(token, options)
token
: string - The JWT token to validate.options
Object (optional): Validation options. VerifyOptions from the jsonwebtoken
library with additional properties.
allowedTenants
string[] (optional): The allowed tenants for the JWT token. Compared against the tid
claim.idtyp
string (optional): The idtyp claim to be validated against.roles
string[] (optional): Roles expected in the 'roles' claim in the JWT token.scp
string[] (optional): Scopes expected in the 'scp' claim in the JWT token.ver
: string (optional) - The version claim to be validated against.Promise<JwtPayload | string>
- The decoded and verified JWT token.Error
- If the token is invalid or the validation fails.clearCache()
deleteKey(kid)
kid
string - The key ID to delete from the cache.getEntraJwksUri(tenant, cloud)
tenant
string (optional, default=common
) - The tenant to get the JWKS URL for.cloud
string (optional, default=CloudType.Public
) - The cloud to get the JWKS URL for.Promise<string>
- The JWKS URI.CloudType
Public
- Microsoft Azure public cloud.Ppe
- Microsoft PPE.USGovernment
- US Government cloud.China
- Microsoft Chinese national/regional cloud.This project is licensed under the MIT License.
FAQs
Validate JWT tokens in Node.js.
We found that jwt-validate demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket now integrates with Bun 1.3’s Security Scanner API to block risky packages at install time and enforce your organization’s policies in local dev and CI.
Research
The Socket Threat Research Team is tracking weekly intrusions into the npm registry that follow a repeatable adversarial playbook used by North Korean state-sponsored actors.
Security News
A data handling bug in OSV.dev caused disputed CVEs to disappear from vulnerability feeds until a recent fix restored over 500 advisories.