Gathering detailed insights and metrics for aws-jwt-verify
Gathering detailed insights and metrics for aws-jwt-verify
Gathering detailed insights and metrics for aws-jwt-verify
Gathering detailed insights and metrics for aws-jwt-verify
fastify-aws-jwt-verify
Fastify plugin wrapper around aws-jwt-verify for JWT authentication/authorization with AWS Cognito
passport-jwt
Passport authentication strategy using JSON Web Tokens
jose
JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes
express-jwt
JWT authentication middleware.
JS library for verifying JWTs signed by Amazon Cognito, and any OIDC-compatible IDP that signs JWTs with RS256, RS384, RS512, ES256, ES384, and ES512
npm install aws-jwt-verify
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
633 Stars
119 Commits
45 Forks
14 Watching
1 Branches
18 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
TypeScript (94.72%)
JavaScript (3.67%)
Shell (0.92%)
HTML (0.5%)
CSS (0.19%)
Cumulative downloads
Total Downloads
Last day
-2.2%
56,515
Compared to previous day
Last week
-1.7%
280,290
Compared to previous week
Last month
-2.1%
1,280,459
Compared to previous month
Last year
138.6%
13,248,824
Compared to previous year
JavaScript library for verifying JWTs signed by Amazon Cognito, and any OIDC-compatible IDP that signs JWTs with RS256 / RS384 / RS512 / ES256 / ES384 / ES512.
npm install aws-jwt-verify
This library can be used with Node.js 14 or higher. If used with TypeScript, TypeScript 4 or higher is required.
This library can also be used in Web browsers.
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2 3// Verifier that expects valid access tokens: 4const verifier = CognitoJwtVerifier.create({ 5 userPoolId: "<user_pool_id>", 6 tokenUse: "access", 7 clientId: "<client_id>", 8}); 9 10try { 11 const payload = await verifier.verify( 12 "eyJraWQeyJhdF9oYXNoIjoidk..." // the JWT as string 13 ); 14 console.log("Token is valid. Payload:", payload); 15} catch { 16 console.log("Token not valid!"); 17}
See all verify parameters for Amazon Cognito JWTs here.
1import { JwtVerifier } from "aws-jwt-verify"; 2 3const verifier = JwtVerifier.create({ 4 issuer: "https://example.com/", // set this to the expected "iss" claim on your JWTs 5 audience: "<audience>", // set this to the expected "aud" claim on your JWTs 6 jwksUri: "https://example.com/.well-known/jwks.json", // set this to the JWKS uri from your OpenID configuration 7}); 8 9try { 10 const payload = await verifier.verify("eyJraWQeyJhdF9oYXNoIjoidk..."); 11 console.log("Token is valid. Payload:", payload); 12} catch { 13 console.log("Token not valid!"); 14}
See all verify parameters for JWTs from any IDP here.
issuer
and audience
, as these should be checked for (see best practices linked to above).Currently, signature algorithms RS256 , RS384 , RS512 and ES256 , ES384 , ES512 are supported.
This library was specifically designed to be easy to use in:
Many webdev toolchains (e.g. CreateReactApp) make including npm
libraries in your web app easy, in which case using this library in your web app should just work.
If you need to bundle this library manually yourself, be aware that this library uses subpath imports, to automatically select the Web crypto implementation when bundling for the browser. This is supported out-of-the-box by webpack and esbuild. An example of using this library in a Vite web app, with Cypress tests, is included in this repository here.
alg
) is selected to verify the JWT signature withFetcher
with SimpleJwksCache
Fetcher
penaltyBox
with SimpleJwksCache
Create a CognitoJwtVerifier
instance and use it to verify JWTs:
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2 3// Verifier that expects valid access tokens: 4const verifier = CognitoJwtVerifier.create({ 5 userPoolId: "<user_pool_id>", 6 tokenUse: "access", 7 clientId: "<client_id>", 8}); 9 10try { 11 const payload = await verifier.verify( 12 "eyJraWQeyJhdF9oYXNoIjoidk..." // the JWT as string 13 ); 14 console.log("Token is valid. Payload:", payload); 15} catch { 16 console.log("Token not valid!"); 17}
You can also use verifySync
, if you've made sure the JWK has already been cached, see further below.
CognitoJwtVerifier
verify
parametersExcept the User Pool ID, parameters provided when creating the CognitoJwtVerifier
act as defaults, that can be overridden upon calling verify
or verifySync
.
Supported parameters are:
tokenUse
(mandatory): verify that the JWT's token_use
claim matches your expectation. Set to either id
or access
. Set to null
to skip checking token_use
.clientId
(mandatory): verify that the JWT's aud
(id token) or client_id
(access token) claim matches your expectation. Provide a string, or an array of strings to allow multiple client ids (i.e. one of these client ids must match the JWT). Set to null
to skip checking client id (not recommended unless you know what you are doing).groups
(optional): verify that the JWT's cognito:groups
claim matches your expectation. Provide a string, or an array of strings to allow multiple groups (i.e. one of these groups must match the JWT).scope
(optional): verify that the JWT's scope
claim matches your expectation (only of use for access tokens). Provide a string, or an array of strings to allow multiple scopes (i.e. one of these scopes must match the JWT). See also Checking scope.graceSeconds
(optional, default 0
): to account for clock differences between systems, provide the number of seconds beyond JWT expiry (exp
claim) or before "not before" (nbf
claim) you will allow.customJwtCheck
(optional): your custom function with additional JWT (and JWK) checks to execute (see also below).includeRawJwtInErrors
(optional, default false
): set to true
if you want to peek inside the invalid JWT when verification fails. Refer to: Peek inside invalid JWTs.1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2 3const verifier = CognitoJwtVerifier.create({ 4 userPoolId: "<user_pool_id>", // mandatory, can't be overridden upon calling verify 5 tokenUse: "id", // needs to be specified here or upon calling verify 6 clientId: "<client_id>", // needs to be specified here or upon calling verify 7 groups: "admins", // optional 8 graceSeconds: 0, // optional 9 scope: "my-api/read", // optional 10 customJwtCheck: (payload, header, jwk) => {}, // optional 11}); 12 13try { 14 const payload = await verifier.verify("eyJraWQeyJhdF9oYXNoIjoidk...", { 15 groups: "users", // Cognito groups overridden: should be users (not admins) 16 }); 17 console.log("Token is valid. Payload:", payload); 18} catch { 19 console.log("Token not valid!"); 20}
If you provide scopes to the CognitoJwtVerifier
, the verifier will make sure the scope
claim in the JWT includes at least one of those scopes:
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2 3const verifier = CognitoJwtVerifier.create({ 4 userPoolId: "<user_pool_id>", 5 tokenUse: "access", // scopes are only present on Cognito access tokens 6 clientId: "<client_id>", 7 scope: ["my-api:write", "my-api:admin"], 8}); 9 10try { 11 const payload = await verifier.verify("eyJraWQeyJhdF9oYXNoIjoidk..."); 12 console.log("Token is valid. Payload:", payload); 13} catch { 14 console.log("Token not valid!"); 15}
So a JWT payload like the following would have a valid scope:
1{ 2 "client_id": "<client_id>", 3 "scope": "my-api:write someotherscope yetanotherscope", // scope string is split on spaces to gather the array of scopes to compare with 4 "iat": 1234567890, 5 "...": "..." 6}
This scope would not be valid:
1{ 2 "client_id": "<client_id>", 3 "scope": "my-api:read someotherscope yetanotherscope", // Neither "my-api:write" nor "my-api:admin" present 4 "iat": 1234567890, 5 "...": "..." 6}
It's possible to provide a function with your own custom JWT checks. This function will be called if the JWT is valid, at the end of the JWT verification.
The function will be called with:
Throw an error in this function if you want to reject the JWT.
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2 3const idTokenVerifier = CognitoJwtVerifier.create({ 4 userPoolId: "<user_pool_id>", 5 tokenUse: "id", 6 clientId: "<client_id>", 7 customJwtCheck: async ({ header, payload, jwk }) => { 8 if (header.someHeaderField !== "expected") { 9 throw new Error("something wrong with the header"); 10 } 11 if (payload.somePayloadField !== "expected") { 12 throw new Error("something wrong with the payload"); 13 } 14 if (jwk.someJwkfField !== "expected") { 15 throw new Error("something wrong with the jwk"); 16 } 17 await someAsyncCheck(...); // can call out to a DB or do whatever 18 }, 19}); 20 21// This will now throw, even if the JWT is otherwise valid, if your custom function throws: 22await idTokenVerifier.verify("eyJraWQeyJhdF9oYXNoIjoidk...");
Note that customJwtCheck
may be an async function, but only if you use verify
(not supported for verifySync
).
If you want to allow JWTs from multiple User Pools, provide an array with these User Pools upon creating the verifier:
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2 3// This verifier will trust both User Pools 4const idTokenVerifier = CognitoJwtVerifier.create([ 5 { 6 userPoolId: "<user_pool_id>", 7 tokenUse: "id", 8 clientId: "<client_id>", // clientId is mandatory at verifier level now, to disambiguate between User Pools 9 }, 10 { 11 userPoolId: "<user_pool_id_2>", 12 tokenUse: "id", 13 clientId: "<client_id_2>", 14 }, 15]); 16 17try { 18 const idTokenPayload = await idTokenVerifier.verify( 19 "eyJraWQeyJhdF9oYXNoIjoidk..." // token must be signed by either of the User Pools 20 ); 21 console.log("Token is valid. Payload:", idTokenPayload); 22} catch { 23 console.log("Token not valid!"); 24}
The generic JwtVerifier
(see below) can also be used for Cognito, which is useful if you want to define a verifier that trusts multiple IDPs, i.e. Cognito and another IDP.
In this case, leave audience
to null
, but rather manually add validateCognitoJwtFields
in the customJwtCheck
.
(Only Cognito ID tokens have an audience
claim, Cognito Access token have a client_id
claim instead. The validateCognitoJwtFields
function handles this difference automatically for you)
1import { JwtVerifier } from "aws-jwt-verify"; 2import { validateCognitoJwtFields } from "aws-jwt-verify/cognito-verifier"; 3 4const verifier = JwtVerifier.create([ 5 { 6 issuer: "https://cognito-idp.eu-west-1.amazonaws.com/<user_pool_id>", 7 audience: null, // audience (~clientId) is checked instead, by the Cognito specific checks below 8 customJwtCheck: ({ payload }) => 9 validateCognitoJwtFields(payload, { 10 tokenUse: "access", // set to "id" or "access" (or null if both are fine) 11 clientId: "<client_id>", // provide the client id, or an array of client ids (or null if you do not want to check client id) 12 groups: ["admin", "others"], // optional, provide a group name, or array of group names 13 }), 14 }, 15 { 16 issuer: "https://example.com/my/other/idp", 17 audience: "myaudience", // do specify audience for other IDPs 18 }, 19]);
The generic JwtVerifier
works for any OIDC-compatible IDP that signs JWTs with RS256/RS384/RS512/ES256/ES384/ES512:
1import { JwtVerifier } from "aws-jwt-verify"; 2 3const verifier = JwtVerifier.create({ 4 issuer: "https://example.com/", // set this to the expected "iss" claim on your JWTs 5 audience: "<audience>", // set this to the expected "aud" claim on your JWTs 6 jwksUri: "https://example.com/.well-known/jwks.json", // set this to the JWKS uri from your OpenID configuration 7}); 8 9try { 10 const payload = await verifier.verify("eyJraWQeyJhdF9oYXNoIjoidk..."); 11 console.log("Token is valid. Payload:", payload); 12} catch { 13 console.log("Token not valid!"); 14}
Support Multiple IDP's:
1const verifier = JwtVerifier.create([ 2 { 3 issuer: "https://example.com/idp1", 4 audience: "expectedAudienceIdp1", 5 }, 6 { 7 issuer: "https://example.com/idp2", 8 audience: "expectedAudienceIdp2", 9 }, 10]); 11 12try { 13 const otherPayload = await verifier.verify("eyJraWQeyJhdF9oYXNoIjoidk..."); // Token must be from either idp1 or idp2 14 console.log("Token is valid. Payload:", otherPayload); 15} catch { 16 console.log("Token not valid!"); 17}
JwtVerifier
verify
parametersExcept issuer
, parameters provided when creating the JwtVerifier
act as defaults, that can be overridden upon calling verify
or verifySync
.
Supported parameters are:
jwksUri
(optional, can only be provided at verifier level): the URI where the JWKS can be downloaded from. To find this URI for your IDP, consult your IDP's OpenId configuration (e.g. by opening the OpenId configuration in your browser). Usually, it is ${issuer}/.well-known/jwks.json
, which is the default value that will be used if you don't explicitly provide jwksUri
.audience
(mandatory): verify that the JWT's aud
claim matches your expectation. Provide a string, or an array of strings to allow multiple client ids (i.e. one of these audiences must match the JWT). Set to null
to skip checking audience (not recommended unless you know what you are doing). Note that a JWT's aud
claim might be an array of audiences. The JwtVerifier
will in that case make sure that at least one of these audiences matches with at least one of the audiences that were provided to the verifier.scope
(optional): verify that the JWT's scope
claim matches your expectation (only of use for access tokens). Provide a string, or an array of strings to allow multiple scopes (i.e. one of these scopes must match the JWT). See also Checking scope.graceSeconds
(optional, default 0
): to account for clock differences between systems, provide the number of seconds beyond JWT expiry (exp
claim) or before "not before" (nbf
claim) you will allow.customJwtCheck
(optional): your custom function with additional JWT checks to execute (see Custom JWT and JWK checks).includeRawJwtInErrors
(optional, default false
): set to true
if you want to peek inside the invalid JWT when verification fails. Refer to: Peek inside invalid JWTs.alg
) is selected to verify the JWT signature withaws-jwt-verify
does not require users to specify the algorithm (alg
) to verify JWT signatures with. Rather, the alg
is selected automatically from the JWT header, and matched against the alg
(if any) on the selected JWK. We believe this design decision makes it easier to use this library: one less parameter to provide, that developers potentially would not know which value to provide for.
To readers who are intimately aware of how JWT verification in general should work, this design decision may seem dubious, because the JWT header, and thus the alg
in it, would be under potential threat actor control. But this is mitigated because aws-jwt-verify
only allows a limited set of algorithms anyway, all asymmetric: RS256, RS384, RS512, ES256, ES384, ES512. The egregious case of alg
with value none
is explicitly not supported, nor are symmetric algorithms, and such JWTs would be considered invalid.
If the JWK that's selected for verification (see The JWKS cache) has an alg
, it must match the JWT header's alg
, or the JWT is considered invalid. alg
is an optional JWK field, but in practice present in most implementations (such as Amazon Cognito User Pools).
alg
)If you really want to enforce a certain alg
, you should use a JWKS that only contains JWKs which have that alg
explicitly specified.
If the JWKS is not under your control, you can customize the way your JWKS is used by customizing the JWKS cache. E.g. you could explicitly set the alg
value on each JWK, or filter the JWKS to only those JWKs that have a specific alg
, such as in the example below:
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2import { SimpleJwksCache } from "aws-jwt-verify/jwk"; 3 4class Rs256OnlyJwksCache extends SimpleJwksCache { 5 async getJwks(jwksUri: string) { 6 const jwks = await super.getJwks(jwksUri); 7 // filter JWKS to RS256 only 8 jwks.keys = jwks.keys.filter((jwk) => jwk.alg === "RS256"); 9 return jwks; 10 } 11} 12 13const verifier = CognitoJwtVerifier.create( 14 { 15 userPoolId: "<user_pool_id>", 16 tokenUse: "access", 17 clientId: "<client_id>", 18 }, 19 { 20 jwksCache: new Rs256OnlyJwksCache(), 21 } 22);
You can peek into the payload of an unverified JWT as follows.
Note: this does NOT verify a JWT, do not trust the returned payload and header! For most use cases, you would not want to call this function directly yourself, rather you would call verify()
with the JWT, which would call this function (and others) for you.
1import { decomposeUnverifiedJwt } from "aws-jwt-verify/jwt"; 2 3// danger! payload is sanity checked and JSON-parsed, but otherwise unverified, trust nothing in it! 4const { payload } = decomposeUnverifiedJwt( 5 "eyJraWQeyJhdF9oYXNoIjoidk..." // the JWT as string 6);
When verification of a JWT fails, this library will throw an error. All errors are defined in src/error.ts and can be imported and tested for like so:
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2import { JwtExpiredError } from "aws-jwt-verify/error"; 3 4const verifier = CognitoJwtVerifier.create({ 5 userPoolId: "<user_pool_id>", 6 tokenUse: "access", 7 clientId: "<client_id>", 8}); 9 10try { 11 const payload = await verifier.verify( 12 "eyJraWQeyJhdF9oYXNoIjoidk..." // the JWT as string 13 ); 14} catch (err) { 15 // An error is thrown, so the JWT is not valid 16 // Use `instanceof` to test for specific error cases: 17 if (err instanceof JwtExpiredError) { 18 console.error("JWT expired!"); 19 } 20 throw err; 21}
If you want to peek inside invalid JWTs, set includeRawJwtInErrors
to true
when creating the verifier. The thrown error will then include the raw JWT:
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2import { JwtInvalidClaimError } from "aws-jwt-verify/error"; 3 4const verifier = CognitoJwtVerifier.create({ 5 userPoolId: "<user_pool_id>", 6 tokenUse: "access", 7 clientId: "<client_id>", 8 includeRawJwtInErrors: true, // can also be specified as parameter to the `verify` call 9}); 10 11try { 12 const payload = await verifier.verify( 13 "eyJraWQeyJhdF9oYXNoIjoidk..." // the JWT as string 14 ); 15} catch (err) { 16 if (err instanceof JwtInvalidClaimError) { 17 // You can log the payload of the raw JWT, e.g. to aid in debugging and alerting on authentication errors 18 // Be careful not to disclose information on the error reason to the the client 19 console.error("JWT invalid because:", err.message); 20 console.error("Raw JWT:", err.rawJwt.payload); 21 } 22 throw new Error("Unauthorized"); 23}
The instanceof
check in the catch
block above is crucial, because not all errors will include the rawJwt, only errors that subclass JwtInvalidClaimError
will. In order to understand why this makes sense, you should know that this library verifies JWTs in 3 stages, that all must succeed for the JWT to be considered valid:
Only in case of stage 3 verification errors, will the raw JWT be included in the error (if you set includeRawJwtInErrors
to true
). This way, when you look at the invalid raw JWT in the error, you'll know that its structure and signature are at least valid (stages 1 and 2 succeeded).
Note that if you use custom JWT checks, you are in charge of throwing errors in your custom code. You can (optionally) subclass your errors from JwtInvalidClaimError
, so that the raw JWT will be included on the errors you throw as well:
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2import { JwtInvalidClaimError } from "aws-jwt-verify/error"; 3 4class CustomError extends JwtInvalidClaimError {} 5 6const verifier = CognitoJwtVerifier.create({ 7 userPoolId: "<user_pool_id>", 8 tokenUse: "access", 9 clientId: "<client_id>", 10 includeRawJwtInErrors: true, 11 customJwtCheck: ({ payload }) => { 12 if (payload.custom_claim !== "expected") 13 throw new CustomError("Invalid JWT", payload.custom_claim, "expected"); 14 }, 15}); 16 17try { 18 const payload = await verifier.verify( 19 "eyJraWQeyJhdF9oYXNoIjoidk..." // the JWT as string 20 ); 21} catch (err) { 22 if (err instanceof JwtInvalidClaimError) { 23 console.error("JWT invalid:", err.rawJwt.payload); 24 } 25 throw new Error("Unauthorized"); 26}
The JWKS cache is responsible for fetching the JWKS from the JWKS URI, caching it, and selecting the right JWK from it. Both the CognitoJwtVerifier
and the (generic) JwtVerifier
utilize an in-memory JWKS cache. For each issuer
a JWKS cache is maintained, and each JWK in a JWKS is selected and cached using its kid
(key id). The JWKS for an issuer
will be fetched once initially, and thereafter only upon key rotations (detected by the occurrence of a JWT with a kid
that is not yet in the cache).
Note: examples below work the same for CognitoJwtVerifier
and JwtVerifier
.
If e.g. your runtime environment doesn't have internet access, or you want to prevent the fetch over the network, you can load the JWKS explicitly yourself:
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2import { readFileSync } from "fs"; 3 4const idTokenVerifier = CognitoJwtVerifier.create({ 5 userPoolId: "<user_pool_id>", 6 tokenUse: "id", 7 clientId: "<client_id>", 8}); 9 10const jwks = JSON.parse(readFileSync("jwks.json", { encoding: "utf-8" })); 11idTokenVerifier.cacheJwks(jwks); 12 13// Because the JWKS doesn't need to be downloaded now, you can use verifySync: 14try { 15 const idTokenPayload = idTokenVerifier.verifySync( 16 "eyJraWQeyJhdF9oYXNoIjoidk..." 17 ); 18 console.log("Token is valid. Payload:", payload); 19} catch { 20 console.log("Token not valid!"); 21} 22 23// Async verify will of course work as well (and will use the cache also): 24try { 25 const idTokenPayload = await idTokenVerifier.verify( 26 "eyJraWQeyJhdF9oYXNoIjoidk..." 27 ); 28 console.log("Token is valid. Payload:", idTokenPayload); 29} catch { 30 console.log("Token not valid!"); 31}
Note that the verifier will still try to fetch the JWKS, if it encounters a JWT with a kid that is not in it's cached JWKS (i.e. to cater for key rotations).
Both the CognitoJwtVerifier
and the JwtVerifier
enforce a rate limit of 1 JWKS download per JWKS uri per 10 seconds. This protects users of this library from inadvertently flooding the JWKS uri with requests, and prevents wasting time doing network calls.
The rate limit works as follows (implemented by the penaltyBox
, see below). When the verifier fetches the JWKS and fails to locate the JWT's kid in the JWKS, an error is thrown, and a timer of 10 seconds is started. Until that timer completes, the verifier will refuse to fetch the particular JWKS uri again. It will instead throw an error immediately on verify
calls where that would require the JWKS to be downloaded.
The verifier will continue to verify JWTs for which the right JWK is already present in the cache, also it will still try other JWKS uris (for other issuers).
It is possible to implement a different rate limiting scheme yourself, by customizing the JWKS cache, or the penaltyBox
implementation, see below.
In a long running Node.js API (e.g. a Fargate container), it might make sense to hydrate the JWKS cache upon server start up. This will speed up the first JWT verification, as the JWKS doesn't have to be downloaded anymore.
This call will always fetch the current, latest, JWKS for each of the verifier's issuers (even though the JWKS might have been fetched and cached before):
1const verifier = JwtVerifier.create([ 2 { 3 issuer: "https://example.com/idp1", 4 audience: "myappclient1", 5 }, 6 { 7 issuer: "https://example.com/idp2", 8 audience: "myappclient2", 9 }, 10]); 11 12// Fetch and cache the JWKS for all configured issuers 13await verifier.hydrate();
Note: it is only useful to call this method if your calling process has an idle time window, in which it might just as well fetch the JWKS. For example, during container start up, when the load balancer does not yet route traffic to the container. Calling this method inside API Gateway custom authorizers or Lambda@Edge has no benefit (in fact, awaiting the call as part of the Lambda handler would even hurt performance as it bypasses the existing cached JWKS).
If you have a predefined rotation schedule for your JWKS, you could set the refresh interval of the verifier aligned to this schedule:
1import { JwtVerifier } from "aws-jwt-verify"; 2 3const verifier = JwtVerifier.create({ 4 issuer: "https://example.com/", 5 audience: "<audience>", 6}); 7 8setInterval( 9 () => { 10 verifier.cacheJwks({ keys: [] }); // empty cache, by loading an empty JWKS 11 }, 12 1000 * 60 * 60 * 4 13); // For a 4 hour refresh schedule
If an automated rotation does not fit your use case, and you need to clear out the JWKS cache, you could use:
1verifier.cacheJwks({ keys: [] });
When you instantiate a CognitoJwtVerifier
or JwtVerifier
without providing a JwksCache
, the SimpleJwksCache
is used:
1import { JwtVerifier } from "aws-jwt-verify"; 2import { SimpleJwksCache } from "aws-jwt-verify/jwk"; 3 4const verifier = JwtVerifier.create({ 5 issuer: "http://my-tenant.my-idp.com", 6}); 7 8// Equivalent: 9const verifier2 = JwtVerifier.create( 10 { 11 issuer: "http://my-tenant.my-idp.com", 12 }, 13 { 14 jwksCache: new SimpleJwksCache(), 15 } 16);
The SimpleJwksCache
can be tailored by using a different penaltyBox
and/or fetcher
(see below).
Alternatively, you can implement an entirely custom JwksCache
yourself, by creating a class that implements the interface JwksCache
(from "aws-jwt-verify/jwk"
). This allows for highly custom scenario's, e.g. you could implement a JwksCache
with custom logic for selecting a JWK from the JWKS.
If you want to define multiple verifiers for the same JWKS uri, it makes sense to share the JWKS cache, so the JWKS will be downloaded and cached once:
1import { JwtVerifier } from "aws-jwt-verify"; 2import { SimpleJwksCache } from "aws-jwt-verify/jwk"; 3 4const sharedJwksCache = new SimpleJwksCache(); 5 6const verifierA = JwtVerifier.create( 7 { 8 jwksUri: "https://example.com/keys/jwks.json", 9 issuer: "https://example.com/", 10 audience: "<audience>", 11 }, 12 { 13 jwksCache: sharedJwksCache, 14 } 15); 16 17const verifierB = JwtVerifier.create( 18 { 19 jwksUri: "https://example.com/keys/jwks.json", // same JWKS URI, so sharing cache makes sense 20 issuer: "https://example.com/", 21 audience: "<audience>", 22 }, 23 { 24 jwksCache: sharedJwksCache, 25 } 26);
Fetcher
with SimpleJwksCache
When instantiating SimpleJwksCache
, the fetcher
property can be populated with an instance of a class that implements the interface Fetcher
(from "aws-jwt-verify/https"
), such as the SimpleFetcher
(which is the default).
The purpose of the fetcher, is to execute fetches against the JWKS uri (HTTPS GET) and return the response as an arraybuffer (that will be UTF-8 decoded and JSON parsed by the SimpleJwksCache
).
The default implementation, the SimpleFetcher
, has basic machinery to do fetches over HTTPS. It does 1 (immediate) retry in case of connection errors.
By supplying a custom fetcher when instantiating SimpleJwksCache
, instead of SimpleFetcher
, you can implement any retry and backoff scheme you want, or use another HTTPS library:
1import { JwtVerifier } from "aws-jwt-verify"; 2import { SimpleJwksCache } from "aws-jwt-verify/jwk"; 3import { Fetcher } from "aws-jwt-verify/https"; 4import axios from "axios"; 5 6// Use axios to do the HTTPS fetches 7class CustomFetcher implements Fetcher { 8 instance = axios.create(); 9 public async fetch(uri: string) { 10 return this.instance 11 .get(uri, { responseType: "arraybuffer" }) 12 .then((response) => response.data); 13 } 14} 15 16const verifier = JwtVerifier.create( 17 { 18 issuer: "http://my-tenant.my-idp.com", 19 }, 20 { 21 jwksCache: new SimpleJwksCache({ 22 fetcher: new CustomFetcher(), 23 }), 24 } 25);
JwksParser
with SimpleJwksCache
The default JwksParser
takes the ArrayBuffer
that the fetcher (see above) returns, and UTF-8 decodes and JSON parses it, and verifies it is a valid JWKS.
If your JWKS is non-standard, you can override the parser, giving you the option to do any transformations needed to make it a standard JWKS:
1import { JwtVerifier } from "aws-jwt-verify"; 2import { SimpleJwksCache, assertIsJwks } from "aws-jwt-verify/jwk"; 3 4const verifier = JwtVerifier.create( 5 { 6 issuer: "http://my-tenant.my-idp.com", 7 }, 8 { 9 jwksCache: new SimpleJwksCache({ 10 jwksParser: (buf) => { 11 // This is roughly what the default JwksParser does, 12 // override with your own logic as needed: 13 const jwks = JSON.parse(new TextDecoder().decode(buf)); 14 assertIsJwks(jwks); 15 return jwks; 16 }, 17 }), 18 } 19);
Fetcher
The following configurations are equivalent, use the latter one to set a custom fetch timeout and other HTTP options.
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2 3// No jwksCache configured explicitly, 4// so the default `SimpleJwksCache` with `SimpleFetcher` will be used, 5// with a default response timeout of 3000 ms.: 6const verifier = CognitoJwtVerifier.create({ 7 userPoolId: "<user_pool_id>", 8 tokenUse: "access", // or "id" 9 clientId: "<client_id>", 10});
Equivalent explicit configuration:
1import { CognitoJwtVerifier } from "aws-jwt-verify"; 2import { SimpleJwksCache } from "aws-jwt-verify/jwk"; 3import { Fetcher } from "aws-jwt-verify/https"; 4 5const verifier = CognitoJwtVerifier.create( 6 { 7 userPoolId: "<your user pool id>", 8 tokenUse: "access", // or "id", 9 clientId: "<your client id>", 10 }, 11 { 12 jwksCache: new SimpleJwksCache({ 13 fetcher: new SimpleFetcher({ 14 defaultRequestOptions: { 15 responseTimeout: 3000, 16 // You can add additional request options: 17 // For NodeJS: https://nodejs.org/api/http.html#httprequestoptions-callback 18 // For Web (init object): https://developer.mozilla.org/en-US/docs/Web/API/fetch#syntax 19 }, 20 }), 21 }), 22 } 23);
penaltyBox
with SimpleJwksCache
When instantiating SimpleJwksCache
, the penaltyBox
property can be populated with an instance of a class that implements the interface PenaltyBox
(from "aws-jwt-verify/jwk"
), such as the SimplePenaltyBox
(which is the default).
The SimpleJwksCache
will always do await penaltyBox.wait(jwksUri, kid)
before asking the fetcher
to fetch the JWKS.
By supplying a custom penaltyBox when instantiating SimpleJwksCache
, instead of SimplePenaltyBox
, you can implement any waiting scheme you want, in your implementation of the wait
function.
The SimpleJwksCache
will call penaltyBox.registerSuccessfulAttempt(jwksUri, kid)
when it succeeds in locating the right JWK in the JWKS, and call penaltyBox.registerFailedAttempt(jwksUri, kid)
otherwise. You need to process these calls, so that you can determine the right amount of waiting in your wait
implementation.
1import { JwtVerifier } from "aws-jwt-verify"; 2import { 3 SimpleJwksCache, 4 SimplePenaltyBox, 5 PenaltyBox, 6} from "aws-jwt-verify/jwk"; 7 8// In this example we use the SimplePenaltyBox, but override the default wait period 9const verifier = JwtVerifier.create( 10 { 11 issuer: "http://my-tenant.my-idp.com", 12 }, 13 { 14 jwksCache: new SimpleJwksCache({ 15 penaltyBox: new SimplePenaltyBox({ waitSeconds: 1 }), 16 }), 17 } 18); 19 20// Or implement your own penaltyBox 21// The example here just stupidly waits 5 second always, 22// even on the first fetch of the JWKS uri 23class CustomPenaltyBox implements PenaltyBox { 24 public async wait(jwksUri: string, kid: string) { 25 // implement something better 26 await new Promise((resolve) => setTimeout(resolve, 5000)); 27 } 28 public registerFailedAttempt(jwksUri: string, kid: string) { 29 // implement 30 } 31 public registerSuccessfulAttempt(jwksUri: string, kid: string) { 32 // implement 33 } 34} 35const verifier2 = JwtVerifier.create( 36 { 37 issuer: "http://my-tenant.my-idp.com", 38 }, 39 { 40 jwksCache: new SimpleJwksCache({ penaltyBox: new CustomPenaltyBox() }), 41 } 42);
The verifier should be instantiated outside the Lambda handler, so the verifier's cache can be reused for subsequent requests for as long as the Lambda functions stays "hot".
This is an example of a Viewer Request Lambda@Edge function, that inspects each incoming request. It requires each incoming request to have a valid JWT (in this case an access token that includes scope "read") in the HTTP "Authorization" header.
1const { CognitoJwtVerifier } = require("aws-jwt-verify"); 2 3// Create the verifier outside the Lambda handler (= during cold start), 4// so the cache can be reused for subsequent invocations. Then, only during the 5// first invocation, will the verifier actually need to fetch the JWKS. 6const jwtVerifier = CognitoJwtVerifier.create({ 7 userPoolId: "<user_pool_id>", 8 tokenUse: "access", 9 clientId: "<client_id>", 10 scope: "read", 11}); 12 13exports.handler = async (event) => { 14 const { request } = event.Records[0].cf; 15 const accessToken = request.headers["authorization"][0].value; 16 try { 17 await jwtVerifier.verify(accessToken); 18 } catch { 19 return { 20 status: "403", 21 body: "Unauthorized", 22 }; 23 } 24 return request; // allow request to proceed 25};
The verifier should be instantiated outside the Lambda handler, so the verifier's cache can be reused for subsequent requests for as long as the Lambda functions stays "hot".
Two types of API Gateway Lambda authorizers could be created - token based and request-based. For both the types of authorizers, you could use the AWS API Gateway Lambda Authorizer BluePrint as a reference pattern where the token validation could be achieved as follows
For token based authorizers, where lambda event payload is set to Token
and token source is set to (http) Header
with name authorization
:
1const { CognitoJwtVerifier } = require("aws-jwt-verify"); 2 3// Create the verifier outside the Lambda handler (= during cold start), 4// so the cache can be reused for subsequent invocations. Then, only during the 5// first invocation, will the verifier actually need to fetch the JWKS. 6const jwtVerifier = CognitoJwtVerifier.create({ 7 userPoolId: "<user_pool_id>", 8 tokenUse: "access", 9 clientId: "<client_id>", 10 scope: "read", 11}); 12 13exports.handler = async (event) => { 14 const accessToken = event.authorizationToken; 15 16 let payload; 17 try { 18 // If the token is not valid, an error is thrown: 19 payload = await jwtVerifier.verify(accessToken); 20 } catch { 21 // API Gateway wants this *exact* error message, otherwise it returns 500 instead of 401: 22 throw new Error("Unauthorized"); 23 } 24 25 // Proceed with additional authorization logic 26 // ... 27};
For request based authorizers, where lambda event payload is set to Request
and identity source is set to (http) Header
with name authorization
:
1const { CognitoJwtVerifier } = require("aws-jwt-verify"); 2 3// Create the verifier outside the Lambda handler (= during cold start), 4// so the cache can be reused for subsequent invocations. Then, only during the 5// first invocation, will the verifier actually need to fetch the JWKS. 6const jwtVerifier = CognitoJwtVerifier.create({ 7 userPoolId: "<user_pool_id>", 8 tokenUse: "access", 9 clientId: "<client_id>", 10 scope: "read", 11}); 12 13exports.handler = async (event) => { 14 const accessToken = event.headers["authorization"]; 15 16 let payload; 17 try { 18 // If the token is not valid, an error is thrown: 19 payload = await jwtVerifier.verify(accessToken); 20 } catch { 21 // API Gateway wants this *exact* error message, otherwise it returns 500 instead of 401: 22 throw new Error("Unauthorized"); 23 } 24 25 // Proceed with additional authorization logic 26 // ... 27};
An example of a sample HTTP Lambda authorizer is included here as part of the test suite for the solution (format 2.0).
The verifier should be instantiated outside the Lambda handler, so the verifier's cache can be reused for subsequent requests for as long as the Lambda functions stays "hot".
This is an example of AppSync Lambda Authorization function, that validates the JWT is valid (in this case an access token that includes scope "read") along with other authorization business logic
1const { CognitoJwtVerifier } = require("aws-jwt-verify"); 2 3// Create the verifier outside the Lambda handler (= during cold start), 4// so the cache can be reused for subsequent invocations. Then, only during the 5// first invocation, will the verifier actually need to fetch the JWKS. 6const jwtVerifier = CognitoJwtVerifier.create({ 7 userPoolId: "<user_pool_id>", 8 tokenUse: "access", 9 clientId: "<client_id>", 10 scope: "read", 11}); 12 13exports.handler = async (event) => { 14 const accessToken = event.authorizationToken; 15 try { 16 await jwtVerifier.verify(accessToken); 17 } catch { 18 return { 19 isAuthorized: false, 20 }; 21 } 22 //Proceed with additional authorization logic 23};
1const { CognitoJwtVerifier } = require("aws-jwt-verify"); 2const fastify = require("fastify")({ logger: true }); 3 4// Create the verifier outside your route handlers, 5// so the cache is persisted and can be shared amongst them. 6const jwtVerifier = CognitoJwtVerifier.create({ 7 userPoolId: "<user_pool_id>", 8 tokenUse: "access", 9 clientId: "<client_id>", 10 scope: "read", 11}); 12 13fastify.get("/", async (request, reply) => { 14 try { 15 // A valid JWT is expected in the HTTP header "authorization" 16 await jwtVerifier.verify(request.headers.authorization); 17 } catch (authErr) { 18 fastify.log.error(authErr); 19 const err = new Error(); 20 err.statusCode = 403; 21 throw err; 22 } 23 return { private: "only visible to users sending a valid JWT" }; 24}); 25 26const startFastify = async () => { 27 try { 28 await fastify.listen(3000); 29 } catch (err) { 30 fastify.log.error(err); 31 process.exit(1); 32 } 33}; 34 35// Hydrate the JWT verifier, and start Fastify. 36// Hydrating the verifier makes sure the JWKS is loaded into the JWT verifier, 37// so it can verify JWTs immediately without any latency. 38// (Alternatively, just start Fastify, the JWKS will be downloaded when the first JWT is being verified then) 39Promise.all([jwtVerifier.hydrate(), () => fastify.listen(3000)]).catch( 40 (err) => { 41 fastify.log.error(err); 42 process.exit(1); 43 } 44);
1const { CognitoJwtVerifier } = require("aws-jwt-verify"); 2const express = require("express"); 3const app = express(); 4const port = 3000; 5 6// Create the verifier outside your route handlers, 7// so the cache is persisted and can be shared amongst them. 8const jwtVerifier = CognitoJwtVerifier.create({ 9 userPoolId: "<user_pool_id>", 10 tokenUse: "access", 11 clientId: "<client_id>", 12 scope: "read", 13}); 14 15app.get("/", async (req, res, next) => { 16 try { 17 // A valid JWT is expected in the HTTP header "authorization" 18 await jwtVerifier.verify(req.header("authorization")); 19 } catch (err) { 20 console.error(err); 21 return res.status(403).json({ statusCode: 403, message: "Forbidden" }); 22 } 23 res.json({ private: "only visible to users sending a valid JWT" }); 24}); 25 26// Hydrate the JWT verifier, then start express. 27// Hydrating the verifier makes sure the JWKS is loaded into the JWT verifier, 28// so it can verify JWTs immediately without any latency. 29// (Alternatively, just start express, the JWKS will be downloaded when the first JWT is being verified then) 30jwtVerifier 31 .hydrate() 32 .catch((err) => { 33 console.error(`Failed to hydrate JWT verifier: ${err}`); 34 process.exit(1); 35 }) 36 .then(() => 37 app.listen(port, () => { 38 console.log(`Example app listening at http://localhost:${port}`); 39 }) 40 );
See CONTRIBUTING for more information.
This project is licensed under the Apache-2.0 License.
No vulnerabilities found.
No security vulnerabilities found.