
Product
Rust Support Now in Beta
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
@okta/jwt-verifier
Advanced tools
@okta/jwt-verifier is an npm package that provides functionality to verify JSON Web Tokens (JWTs) issued by Okta. It is commonly used in applications to ensure that the tokens being used for authentication and authorization are valid and have not been tampered with.
Verify JWT
This feature allows you to verify the validity of a JWT issued by Okta. The code sample demonstrates how to create an instance of OktaJwtVerifier and use it to verify a JWT.
const OktaJwtVerifier = require('@okta/jwt-verifier');
const oktaJwtVerifier = new OktaJwtVerifier({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}'
});
async function verifyToken(token) {
try {
const jwt = await oktaJwtVerifier.verifyAccessToken(token, 'api://default');
console.log('Token is valid:', jwt);
} catch (err) {
console.log('Token is invalid:', err);
}
}
verifyToken('your-jwt-token');
Custom Claims Verification
This feature allows you to verify a JWT with custom claims. The code sample demonstrates how to verify a JWT with specific audience and issuer claims.
const OktaJwtVerifier = require('@okta/jwt-verifier');
const oktaJwtVerifier = new OktaJwtVerifier({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}'
});
async function verifyTokenWithClaims(token) {
try {
const jwt = await oktaJwtVerifier.verifyAccessToken(token, 'api://default', {
audience: 'api://default',
issuer: 'https://{yourOktaDomain}/oauth2/default'
});
console.log('Token is valid with claims:', jwt);
} catch (err) {
console.log('Token is invalid:', err);
}
}
verifyTokenWithClaims('your-jwt-token');
jsonwebtoken is a popular npm package for signing, verifying, and decoding JSON Web Tokens (JWTs). Unlike @okta/jwt-verifier, it is not specific to Okta and can be used with any JWT. It provides a wide range of functionalities for handling JWTs, including support for various algorithms and custom claims.
jose is a comprehensive library for JSON Web Tokens (JWT), JSON Web Encryption (JWE), and JSON Web Signatures (JWS). It offers a more extensive set of features compared to @okta/jwt-verifier, including support for encryption and signing. It is also not specific to Okta and can be used with any JWT.
passport-jwt is a Passport strategy for authenticating with JSON Web Tokens. It is used in conjunction with the Passport authentication middleware for Node.js. Unlike @okta/jwt-verifier, it is designed to work within the Passport framework and provides a more integrated solution for JWT authentication.
This library verifies Okta access and ID tokens by fetching the public keys from the JWKS endpoint of the authorization server.
This library is for Node.js applications and will not compile into a front-end application. If you need to work with tokens in front-end applications, please see okta-auth-js.
Using Express? Our Express Resource Server Example will show you how to use this library in your Express application.
:heavy_check_mark: The current stable major version series is: 4.x
Version | Status |
---|---|
4.x | :heavy_check_mark: Stable |
3.x | :warning: Retiring on 2025-01-31 |
2.x | :x: Retired |
1.x | :x: Retired |
0.x | :x: Retired |
The latest release can always be found on the [releases page][github-releases].
This library verifies Okta access tokens (issued by Okta Custom Authorization servers) by fetching the public keys from the JWKS endpoint of the authorization server. If the access token is valid it will be converted to a JSON object and returned to your code.
You can learn about access tokens, scopes and claims in our OIDC and OAuth 2.0 API Referece.
Okta Custom Authorization Servers require the API Access Management license. If you are using Okta Org Authorization Servers (which don’t require API Access Management) you can manually validate against the /introspect endpoint ( https://developer.okta.com/docs/reference/api/oidc/#introspect ).
For any access token to be valid, the following are asserted:
exp
claim of the access token).aud
claim matches any expected aud
claim passed to verifyAccessToken()
.iss
claim matches the issuer the verifier is constructed with.To learn more about verification cases and Okta's tokens please read Validate Access Tokens.
This library verifies Okta ID tokens (issued by Okta Custom Authorization servers or Okta Org Authorization Server) by fetching the public keys from the JWKS endpoint of the authorization server. If the token is valid it will be converted to a JSON object and returned to your code.
You can learn about ID tokens, scopes and claims in our OIDC and OAuth 2.0 API Referece.
For any ID token to be valid, the following are asserted:
exp
claim of the ID token).aud
claim matches the expected client ID passed to verifyIdToken()
.iss
claim matches the issuer the verifier is constructed with.nonce
claim matches the expected nonce.To learn more about verification cases and Okta's tokens please read Validate ID Tokens.
For information on how to upgrade between versions of the library, see UPGRADING.md
npm install --save @okta/jwt-verifier
Create a verifier instance, bound to the issuer (authorization server URL):
const OktaJwtVerifier = require('@okta/jwt-verifier');
const oktaJwtVerifier = new OktaJwtVerifier({
issuer: 'https://{yourOktaDomain}/oauth2/default' // required
});
oktaJwtVerifier.verifyAccessToken(accessTokenString, expectedAud)
.then(jwt => {
// the token is valid (per definition of 'valid' above)
console.log(jwt.claims);
})
.catch(err => {
// a validation failed, inspect the error
});
The expected audience passed to verifyAccessToken()
is required, and can be either a string (direct match) or an array of strings (the actual aud
claim in the token must match one of the strings).
// Passing a string for expectedAud
oktaJwtVerifier.verifyAccessToken(accessTokenString, 'api://default')
.then(jwt => console.log('token is valid') )
.catch(err => console.warn('token failed validation') );
oktaJwtVerifier.verifyAccessToken(accessTokenString, [ 'api://special', 'api://default'] )
.then(jwt => console.log('token is valid') )
.catch(err => console.warn('token failed validation') );
oktaJwtVerifier.verifyIdToken(idTokenString, expectedClientId, expectedNonce)
.then(jwt => {
// the token is valid (per definition of 'valid' above)
console.log(jwt.claims);
})
.catch(err => {
// a validation failed, inspect the error
});
The expected client ID passed to verifyIdToken()
is required. Expected nonce value is optional and required if the claim is present in the token body.
verifyIdToken
and verifyAccessToken
:{
header: {
typ: 'JWT',
alg: 'RS256',
kid: 'keyId'
},
claims: {
sub: 'sub',
name: 'name',
email: 'email',
ver: 1,
iss: 'https://foobar.org/oauth2/default',
aud: 'aud',
iat: 1657621175,
exp: 1657624775,
jti: 'jti',
amr: [ 'pwd' ],
idp: 'idp',
nonce: 'nonce',
preferred_username: 'username@foobar.org',
auth_time: 1657621173,
at_hash: 'at_hash'
},
toString: () => 'base64-encoded token',
isExpired: () => Boolean,
isNotBefore: () => Boolean,
{
userMessage: 'Jwt is expired',
jwtString: 'base64-encoded token',
parsedHeader: JwtHeader {
typ: 'JWT',
alg: 'RS256',
kid: 'keyId'
},
parsedBody:
ver: 1,
jti: 'jti',
iss: 'iss',
aud: 'api://default',
iat: 1657621175,
exp: 1657621475,
cid: 'cid',
uid: 'uid',
scp: [ 'openid', 'email', 'profile' ],
auth_time: 1657621173,
sub: 'userame@foobar.org'
},
innerError: undefined
}
For basic use cases, you can ask the verifier to assert a custom set of claims. For example, if you need to assert that this JWT was issued for a given client id:
const verifier = new OktaJwtVerifier({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}'
assertClaims: {
cid: '{clientId}'
}
});
Validation fails and an error is returned if the token does not have the configured claim.
For more complex use cases, you can ask the verifier to assert that a claim includes one or more values. This is useful for array type claims as well as claims that have space-separated values in a string.
You use the form: <claim name>.includes
in the assertClaims
object with an array of values to validate.
For example, if you want to assert that an array claim named groups
includes (at least) Everyone
and Another
, you'd write code like this:
const verifier = new OktaJwtVerifier({
issuer: ISSUER,
clientId: CLIENT_ID,
assertClaims: {
'groups.includes': ['Everyone', 'Another']
}
});
If you want to assert that a space-separated string claim name scp
includes (at least) promos:write
and promos:delete
, you'd write code like this:
const verifier = new OktaJwtVerifier({
issuer: ISSUER,
clientId: CLIENT_ID,
assertClaims: {
'scp.includes': ['promos:write', 'promos:delete']
}
});
The values you want to assert are always represented as an array (the right side of the expression). The claim that you're checking against (the left side of the expression) can have either an array (like groups
) or a space-separated list in a string (like scp
) as its value type.
NOTE: Currently, .includes
is the only supported claim operator.
Custom JWKS URI can be provided. It's useful when JWKS URI cannot be based on Issuer URI:
const verifier = new OktaJwtVerifier({
issuer: 'https://{yourOktaDomain}',
clientId: '{clientId}',
jwksUri: 'https://{yourOktaDomain}/oauth2/v1/keys'
});
cacheMaxAge
option for cache entries.jwksRequestsPerMinute
option.Here is a configuration example that shows the default values:
// All values are default files
const oktaJwtVerifier = new OktaJwtVerifier({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}',
cacheMaxAge: 60 * 60 * 1000, // 1 hour
jwksRequestsPerMinute: 10
});
Set up a SPA and a Web App in your Okta org and testing environment variables by following the Testing section in okta-oidc-js Monorepo's README.
NOTE:
When creating a SPA in your Okta org, please make sure all Implicit
checks have been checked in the General Settings -> Application -> Allowed grant types
section.
Command for running unit test:
yarn test:unit
We welcome contributions to all of our open-source packages. Please see the contribution guide to understand how to structure a contribution.
We use yarn for dependency management when developing this package:
yarn install
FAQs
Easily validate Okta access tokens
The npm package @okta/jwt-verifier receives a total of 190,264 weekly downloads. As such, @okta/jwt-verifier popularity was classified as popular.
We found that @okta/jwt-verifier 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.
Product
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
Product
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
Security News
Socket CEO Feross Aboukhadijeh joins Risky Business Weekly to unpack recent npm phishing attacks, their limited impact, and the risks if attackers get smarter.