{"_id":"@apartly/aws-jwt-verify","_rev":"1-2e0679b7acd14285b3e5d7b9ca4ee18d","name":"@apartly/aws-jwt-verify","dist-tags":{"latest":"3.3.1"},"versions":{"3.3.0":{"name":"@apartly/aws-jwt-verify","version":"3.3.0","description":"Verify RS256/RS384/RS512 signed JSON Web Tokens (JWT)","license":"Apache-2.0","author":{"name":"Amazon Web Services","url":"https://aws.amazon.com"},"main":"dist/cjs/index.js","type":"commonjs","types":"index.d.ts","module":"dist/esm/index.js","exports":{".":{"import":"./dist/esm/index.js","require":"./dist/cjs/index.js","types":"./index.d.ts"},"./asn1":{"import":"./dist/esm/asn1.js","require":"./dist/cjs/asn1.js","types":"./asn1.d.ts"},"./assert":{"import":"./dist/esm/assert.js","require":"./dist/cjs/assert.js","types":"./assert.d.ts"},"./cognito-verifier":{"import":"./dist/esm/cognito-verifier.js","require":"./dist/cjs/cognito-verifier.js","types":"./cognito-verifier.d.ts"},"./error":{"import":"./dist/esm/error.js","require":"./dist/cjs/error.js","types":"./error.d.ts"},"./https":{"import":"./dist/esm/https.js","require":"./dist/cjs/https.js","types":"./https.d.ts"},"./jwk":{"import":"./dist/esm/jwk.js","require":"./dist/cjs/jwk.js","types":"./jwk.d.ts"},"./jwt":{"import":"./dist/esm/jwt.js","require":"./dist/cjs/jwt.js","types":"./jwt.d.ts"},"./jwt-model":{"import":"./dist/esm/jwt-model.js","require":"./dist/cjs/jwt-model.js","types":"./jwt-model.d.ts"},"./jwt-rsa":{"import":"./dist/esm/jwt-rsa.js","require":"./dist/cjs/jwt-rsa.js","types":"./jwt-rsa.d.ts"},"./safe-json-parse":{"import":"./dist/esm/safe-json-parse.js","require":"./dist/cjs/safe-json-parse.js","types":"./safe-json-parse.d.ts"}},"devDependencies":{"@tsconfig/node14":"^1.0.3","@types/jest":"^29.2.5","@typescript-eslint/eslint-plugin":"^5.48.0","@typescript-eslint/parser":"^5.48.0","eslint":"^8.31.0","eslint-plugin-security":"^1.5.0","jest":"^29.3.1","jest-junit":"^15.0.0","nock":"^13.2.9","prettier":"^2.8.1","ts-jest":"^29.0.3","ts-node":"^10.9.1","typescript":"^4.9.4"},"scripts":{"dist:cjs":"tsc --module CommonJS --outDir dist/cjs && echo '{\"type\":\"commonjs\",\"imports\":{\"#node-web-compat\":{\"browser\":\"./node-web-compat-web.js\",\"default\":\"./node-web-compat-node.js\"}}}' > dist/cjs/package.json","dist:esm":"tsc --module ES2020 --outDir dist/esm && echo '{\"type\":\"module\",\"imports\":{\"#node-web-compat\":{\"browser\":\"./node-web-compat-web.js\",\"default\":\"./node-web-compat-node.js\"}}}' > dist/esm/package.json","dist:types":"tsc --declarationDir . --declaration --emitDeclarationOnly","dist":"rm -rf dist && npm run dist:cjs && npm run dist:esm && npm run dist:types","lint:check":"eslint . --ignore-path .gitignore --max-warnings 0","lint":"eslint . --fix --ignore-path .gitignore --max-warnings 0","pack-for-tests":"rm -f aws-jwt-verify.tgz 'aws-jwt-verify-?.?.?.tgz' && npm pack && mv aws-jwt-verify-*.tgz aws-jwt-verify.tgz","prepack":"npm run dist","prettier:check":"prettier --check .","prettier":"prettier -w .","test:all":"npm run prettier:check && npm run lint && npm run test:unit && npm run test:install && npm run test:import && npm run test:browser && npm run test:cognito && npm run test:speed","test:cognito":"cd tests/cognito && npm remove aws-jwt-verify.tgz && npm install --no-save --force --no-package-lock ../../aws-jwt-verify.tgz && npm run test","test:import":"cd tests/import-tests && npm remove aws-jwt-verify.tgz && npm install --no-save --force --no-package-lock ../../aws-jwt-verify.tgz && node esm.mjs && node commonjs.cjs && tsc -v && tsc && node typescript.js && tsc -p tsconfig-nodenext.json && node typescript.js && COMPILE_ERRORS=$(2>&1 tsc -p tsconfig-should-not-compile.json || true) && ([ \"$COMPILE_ERRORS\" != \"\" ] || (echo \"Ooops I did compile successfully :(\"; false))","test:install":"./tests/installation-and-basic-usage/run-tests.sh","test:browser":"cd tests/vite-app && npm remove aws-jwt-verify.tgz && npm install --no-save --force --no-package-lock ../../aws-jwt-verify.tgz && ./run-tests.sh","test:speed":"jest -t \"speed\"","test:unit":"jest --collect-coverage -t \"unit\" --testMatch '**/*.test.ts' --reporters=\"jest-junit\" --reporters=\"default\"","test":"npm run test:unit","tsc":"tsc"},"prettier":{"trailingComma":"es5","tabWidth":2,"semi":true},"repository":{"type":"git","url":"git+https://github.com/awslabs/aws-jwt-verify.git"},"engines":{"node":">=14.0.0"},"gitHead":"b0b13ea766741675a87706973ae6798bc75e4b37","bugs":{"url":"https://github.com/awslabs/aws-jwt-verify/issues"},"homepage":"https://github.com/awslabs/aws-jwt-verify#readme","_id":"@apartly/aws-jwt-verify@3.3.0","_nodeVersion":"16.17.0","_npmVersion":"9.1.3","dist":{"integrity":"sha512-gdT4zHiowZ2EIJl5wtYa4YAeLKz+Lb+ivuT7/IIkBqGgBq2Cp0/l7I5sBN9Q3h3Mdp1ySw/PlQku0LV/XoXn0g==","shasum":"29408cf7db803ca8b1eea8aabc5709fe6cafd2e8","tarball":"https://registry.npmjs.org/@apartly/aws-jwt-verify/-/aws-jwt-verify-3.3.0.tgz","fileCount":53,"unpackedSize":248736,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBZlOBuyVlssdKSdnigG/kaGjaUYCFhCXZZhNsxHX+tbAiEA7eWGkNI/O9woD/FVmmG9xBfcAUAyZHwx1k+kNldKnl0="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjzUJgACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmojnRAAg2nEZYkBEQVUp5VXnAVSKS2t5JzRyYOy3UCijemETM3W/v+j\r\nu8eYlVVYQqnyP99IaU27vstQc6zJn8gH29Itqm6dJkjVxrdVesbRS/LeE4gw\r\nd3TiaeB6FMjOD8EdIEj8ziLuh7F7lvZFfdouUXR4DyLCA/FFfx2/HrdGpuEl\r\nQafFhmWCeZ156K8gcmWvIn1w30PNyTdgPV9OAOqlOOBnQbXbxPoZLvwLstLY\r\n/tOYLhGNaZteeqPlJbP8ihkjb5hoATsmFSI4nOtsSYqy8vR/+/83L0qSX3Yd\r\n5N3nmOGFMDUP5Nd+lv75dbV7NsRhn5m2Dg6Ct3z2/XPoomDxbpNCBt8ke38B\r\nvTuMMhOVD6E8cC039zEv5H6mMORHl9Nu/6bC2Or//HVBf2OtCDKvOjCC7JGk\r\nKDOnlC4mWwdqcmgwseU2WCQb2+wb2eojOO91UIBc0g9DKTj0EMgOG2fxQ6lc\r\n5tGD1u3XjnBXgWP04gHT2wjYgwQQYVTnnG79mkCiW6Us9uyBxOU/U7zVSJ8D\r\nG5DnLg7HvlfLEOCYRWuG8UwZOpYVHoZDe8bAFba5TS8dBwr+8RYi3qObVD5v\r\n6bm6mZ0kWgzvqTZpxM1e5uGcrUxPrWIXKaDipOjvNxVgPghp302xKkEe5mfa\r\nnUofMkQkruw4UCTqteKtAisBkCW+1hhp8g4=\r\n=TlVy\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"apartly","email":"emil@apartly.se"},"directories":{},"maintainers":[{"name":"apartly","email":"emil@apartly.se"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/aws-jwt-verify_3.3.0_1674396256425_0.7915338730370596"},"_hasShrinkwrap":false},"3.3.1":{"name":"@apartly/aws-jwt-verify","version":"3.3.1","description":"Verify RS256/RS384/RS512 signed JSON Web Tokens (JWT)","license":"Apache-2.0","author":{"name":"Amazon Web Services","url":"https://aws.amazon.com"},"main":"dist/cjs/index.js","type":"commonjs","types":"index.d.ts","module":"dist/esm/index.js","exports":{".":{"import":"./dist/esm/index.js","require":"./dist/cjs/index.js","types":"./index.d.ts"},"./asn1":{"import":"./dist/esm/asn1.js","require":"./dist/cjs/asn1.js","types":"./asn1.d.ts"},"./assert":{"import":"./dist/esm/assert.js","require":"./dist/cjs/assert.js","types":"./assert.d.ts"},"./cognito-verifier":{"import":"./dist/esm/cognito-verifier.js","require":"./dist/cjs/cognito-verifier.js","types":"./cognito-verifier.d.ts"},"./error":{"import":"./dist/esm/error.js","require":"./dist/cjs/error.js","types":"./error.d.ts"},"./https":{"import":"./dist/esm/https.js","require":"./dist/cjs/https.js","types":"./https.d.ts"},"./jwk":{"import":"./dist/esm/jwk.js","require":"./dist/cjs/jwk.js","types":"./jwk.d.ts"},"./jwt":{"import":"./dist/esm/jwt.js","require":"./dist/cjs/jwt.js","types":"./jwt.d.ts"},"./jwt-model":{"import":"./dist/esm/jwt-model.js","require":"./dist/cjs/jwt-model.js","types":"./jwt-model.d.ts"},"./jwt-rsa":{"import":"./dist/esm/jwt-rsa.js","require":"./dist/cjs/jwt-rsa.js","types":"./jwt-rsa.d.ts"},"./safe-json-parse":{"import":"./dist/esm/safe-json-parse.js","require":"./dist/cjs/safe-json-parse.js","types":"./safe-json-parse.d.ts"}},"devDependencies":{"@tsconfig/node14":"^1.0.3","@types/jest":"^29.2.5","@typescript-eslint/eslint-plugin":"^5.48.0","@typescript-eslint/parser":"^5.48.0","eslint":"^8.31.0","eslint-plugin-security":"^1.5.0","jest":"^29.3.1","jest-junit":"^15.0.0","nock":"^13.2.9","prettier":"^2.8.1","ts-jest":"^29.0.3","ts-node":"^10.9.1","typescript":"^4.9.4"},"scripts":{"dist:cjs":"tsc --module CommonJS --outDir dist/cjs && echo '{\"type\":\"commonjs\",\"imports\":{\"#node-web-compat\":{\"browser\":\"./node-web-compat-web.js\",\"default\":\"./node-web-compat-node.js\"}}}' > dist/cjs/package.json","dist:esm":"tsc --module ES2020 --outDir dist/esm && echo '{\"type\":\"module\",\"imports\":{\"#node-web-compat\":{\"browser\":\"./node-web-compat-web.js\",\"default\":\"./node-web-compat-node.js\"}}}' > dist/esm/package.json","dist:types":"tsc --declarationDir . --declaration --emitDeclarationOnly","dist":"rm -rf dist && npm run dist:cjs && npm run dist:esm && npm run dist:types","lint:check":"eslint . --ignore-path .gitignore --max-warnings 0","lint":"eslint . --fix --ignore-path .gitignore --max-warnings 0","pack-for-tests":"rm -f aws-jwt-verify.tgz 'aws-jwt-verify-?.?.?.tgz' && npm pack && mv aws-jwt-verify-*.tgz aws-jwt-verify.tgz","prepack":"npm run dist","prettier:check":"prettier --check .","prettier":"prettier -w .","test:all":"npm run prettier:check && npm run lint && npm run test:unit && npm run test:install && npm run test:import && npm run test:browser && npm run test:cognito && npm run test:speed","test:cognito":"cd tests/cognito && npm remove aws-jwt-verify.tgz && npm install --no-save --force --no-package-lock ../../aws-jwt-verify.tgz && npm run test","test:import":"cd tests/import-tests && npm remove aws-jwt-verify.tgz && npm install --no-save --force --no-package-lock ../../aws-jwt-verify.tgz && node esm.mjs && node commonjs.cjs && tsc -v && tsc && node typescript.js && tsc -p tsconfig-nodenext.json && node typescript.js && COMPILE_ERRORS=$(2>&1 tsc -p tsconfig-should-not-compile.json || true) && ([ \"$COMPILE_ERRORS\" != \"\" ] || (echo \"Ooops I did compile successfully :(\"; false))","test:install":"./tests/installation-and-basic-usage/run-tests.sh","test:browser":"cd tests/vite-app && npm remove aws-jwt-verify.tgz && npm install --no-save --force --no-package-lock ../../aws-jwt-verify.tgz && ./run-tests.sh","test:speed":"jest -t \"speed\"","test:unit":"jest --collect-coverage -t \"unit\" --testMatch '**/*.test.ts' --reporters=\"jest-junit\" --reporters=\"default\"","test":"npm run test:unit","tsc":"tsc"},"prettier":{"trailingComma":"es5","tabWidth":2,"semi":true},"repository":{"type":"git","url":"git+https://github.com/awslabs/aws-jwt-verify.git"},"engines":{"node":">=14.0.0"},"gitHead":"d932662706894631207982b7a916b2a38cf7f02f","bugs":{"url":"https://github.com/awslabs/aws-jwt-verify/issues"},"homepage":"https://github.com/awslabs/aws-jwt-verify#readme","_id":"@apartly/aws-jwt-verify@3.3.1","_nodeVersion":"18.12.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-d8/mXNbCU9FQTg7NP5O439A8s08b6JE+P3A9F+nV5RPF92flE+XY7VctB3rsz/gCENELQKXS6NrLlBXYqVeXCA==","shasum":"48ca27af22fafd98661f8e452a2169d08e09fe1e","tarball":"https://registry.npmjs.org/@apartly/aws-jwt-verify/-/aws-jwt-verify-3.3.1.tgz","fileCount":53,"unpackedSize":248742,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDon0R5Id1ex68TEKNb5H5h8FP84dv0bj5Df0bN685QBAiAlLnQbf0YOT1Y7uF90Fwnfu5yw1vnJHFsP8cP+Gw8Q/Q=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJj0Q33ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmrncw//X1ivLpznVcYq36kwVti4GnXZ580312b9CY0CLThuE608+CWd\r\nGSFo8okPxvfRiDFcY+2Ga0hivj7LJ3urMZhh7w+L4g9qIspnaNiuq2FtzlhF\r\nL7kVErCyu9GAX/h9jN3zMFtUT2lcjI4/wte2Sl/BneEntSoZeiOLXZXNknTk\r\n9UMJInrArQ3bvyXUp3q4XDXv5NVXM5PZWWlgZ22csCVpnfkeIjkl109JGfso\r\nwc5ISFWs6Te5dlg7LUF+aV8qsDH+vT48JyAKWwL7vPxhhTzio072sxYSCNjE\r\n/OJw75AMcLTYMnYqSR/sWlE3awG1kqI2jLHRcmfm0z1/Ei53PzGGNqpYG4ik\r\n/zCNivdFZfDZTQ/OxfbSIhNeHsSQ0xvVRHuzo7O8imNrF48C0NAjtDehjwRa\r\nt+zDX87b56CVWNFg9VYaAEEv5vMT6lzWNLHJtodSpmgjHwbrYTAlDpZ/+8Uj\r\nC2SQmtCuBiBYxlRlVLYEftZwHmrpfAY5BO3H2/7uTUWRC3MM4QCBDNplxeh4\r\n7bnOAmfQYtPnUgx6hIwiPXyJa2uOpi8YMPoQbBut3g1k6VuVzFKWublhyPve\r\n+mVIjWc7kGFoKtzGH5NIOvl4kwGTjtGr49POP0eb7/0SQ0VgIFP56EegmeZJ\r\noTYlGjZCKV9y91E1yb9w6IjDJ6uM7EUGH8Q=\r\n=z5aF\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"apartly","email":"emil@apartly.se"},"directories":{},"maintainers":[{"name":"apartly","email":"emil@apartly.se"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/aws-jwt-verify_3.3.1_1674644982822_0.5833529235795358"},"_hasShrinkwrap":false}},"time":{"created":"2023-01-22T14:04:16.361Z","3.3.0":"2023-01-22T14:04:16.590Z","modified":"2023-01-25T11:09:43.075Z","3.3.1":"2023-01-25T11:09:42.972Z"},"maintainers":[{"name":"apartly","email":"emil@apartly.se"}],"description":"Verify RS256/RS384/RS512 signed JSON Web Tokens (JWT)","homepage":"https://github.com/awslabs/aws-jwt-verify#readme","repository":{"type":"git","url":"git+https://github.com/awslabs/aws-jwt-verify.git"},"author":{"name":"Amazon Web Services","url":"https://aws.amazon.com"},"bugs":{"url":"https://github.com/awslabs/aws-jwt-verify/issues"},"license":"Apache-2.0","readme":"# AWS JWT Verify\n\n**JavaScript** library for **verifying** JWTs signed by **Amazon Cognito**, and any **OIDC-compatible IDP** that signs JWTs with **RS256** / **RS384** / **RS512**.\n\n## Installation\n\n`npm install aws-jwt-verify`\n\nThis library can be used with Node.js 14 or higher. If used with TypeScript, TypeScript 4 or higher is required.\n\nThis library can also be used in Web browsers.\n\n## Basic usage\n\n### Amazon Cognito\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\n\n// Verifier that expects valid access tokens:\nconst verifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n});\n\ntry {\n  const payload = await verifier.verify(\n    \"eyJraWQeyJhdF9oYXNoIjoidk...\" // the JWT as string\n  );\n  console.log(\"Token is valid. Payload:\", payload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n```\n\nSee all verify parameters for Amazon Cognito JWTs [here](#cognitojwtverifier-verify-parameters).\n\n### Other IDPs\n\n```typescript\nimport { JwtRsaVerifier } from \"aws-jwt-verify\";\n\nconst verifier = JwtRsaVerifier.create({\n  issuer: \"https://example.com/\", // set this to the expected \"iss\" claim on your JWTs\n  audience: \"<audience>\", // set this to the expected \"aud\" claim on your JWTs\n  jwksUri: \"https://example.com/.well-known/jwks.json\", // set this to the JWKS uri from your OpenID configuration\n});\n\ntry {\n  const payload = await verifier.verify(\"eyJraWQeyJhdF9oYXNoIjoidk...\");\n  console.log(\"Token is valid. Payload:\", payload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n```\n\nSee all verify parameters for JWTs from any IDP [here](#jwtrsaverifier-verify-parameters).\n\n## Philosophy of this library\n\n- Do one thing and do it well. Focus solely on **verifying** JWTs.\n- Pure **TypeScript** library that can be used in **Node.js** v14 and above (both CommonJS and ESM supported), as well in the modern evergreen Web browser.\n- Support both **Amazon Cognito** as well as any other **OIDC-compatible IDP** as first class citizen.\n- **0** runtime dependencies, batteries included. This library includes all necessary code to validate RS256/RS384/RS512-signed JWTs. E.g. it contains a simple (and pluggable) **HTTP** helper to fetch the **JWKS** from the JWKS URI, and it includes a simple **ASN.1** encoder to transform JWKs into **DER-encoded RSA public keys** (in order to verify JWTs with Node.js native crypto calls).\n- Opinionated towards the **best practices** as described by the IETF in [JSON Web Token Best Current Practices](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-jwt-bcp-02#section-3).\n- Make it **easy** for users to use this library in a **secure** way. For example, this library requires users to specify `issuer` and `audience`, as these should be checked for (see best practices linked to above).\n\nCurrently, only signature algorithms **RS256** , **RS384** and **RS512** are supported.\n\n## Intended Usage\n\nThis library was specifically designed to be easy to use in:\n\n- [API Gateway Lambda authorizers](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)\n- [AppSync Lambda authorizers](https://docs.aws.amazon.com/appsync/latest/devguide/security-authz.html#aws-lambda-authorization)\n- [CloudFront Lambda@Edge](https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html)\n- Node.js APIs, e.g. running in AWS Fargate, that need to verify incoming JWTs\n\n## Usage in the Web browser\n\nMany webdev toolchains (e.g. [CreateReactApp](https://github.com/facebook/create-react-app)) make including `npm` libraries in your web app easy, in which case using this library in your web app should just work.\n\nIf you need to bundle this library manually yourself, be aware that this library uses [subpath imports](https://nodejs.org/api/packages.html#subpath-imports), to automatically select the Web crypto implementation when bundling for the browser. This is supported out-of-the-box by [webpack](https://webpack.js.org/) and [esbuild](https://esbuild.github.io/). An example of using this library in a Vite web app, with Cypress tests, is included in this repository [here](tests/vite-app/).\n\n## Table of Contents\n\n- [Verifying JWTs from Amazon Cognito](#Verifying-JWTs-from-Amazon-Cognito)\n  - [Verify parameters](#cognitojwtverifier-verify-parameters)\n  - [Checking scope](#checking-scope)\n  - [Custom JWT and JWK checks](#custom-jwt-and-jwk-checks)\n  - [Trusting multiple User Pools](#trusting-multiple-user-pools)\n  - [Using the generic JWT RSA verifier for Cognito JWTs](#using-the-generic-jwt-rsa-verifier-for-cognito-jwts)\n- [Verifying JWTs from any OIDC-compatible IDP](#verifying-jwts-from-any-oidc-compatible-idp)\n  - [Verify parameters](#jwtrsaverifier-verify-parameters)\n- [Verification errors](#verification-errors)\n  - [Peek inside invalid JWTs](#peek-inside-invalid-jwts)\n- [The JWKS cache](#the-jwks-cache)\n  - [Loading the JWKS from file](#loading-the-jwks-from-file)\n  - [Rate limiting](#rate-limiting)\n  - [Explicitly hydrating the JWKS cache](#explicitly-hydrating-the-jwks-cache)\n  - [Clearing the JWKS cache](#clearing-the-jwks-cache)\n  - [Customizing the JWKS cache](#customizing-the-jwks-cache)\n  - [Sharing the JWKS cache amongst different verifiers](#sharing-the-jwks-cache-amongst-different-verifiers)\n  - [Using a different `JsonFetcher` with `SimpleJwksCache`](#using-a-different-jsonfetcher-with-simplejwkscache)\n  - [Configuring the JWKS response timeout and other HTTP options with `JsonFetcher`](#configuring-the-jwks-response-timeout-and-other-http-options-with-jsonfetcher)\n  - [Using a different `penaltyBox` with `SimpleJwksCache`](#using-a-different-penaltybox-with-simplejwkscache)\n- [Usage examples](#Usage-examples)\n  - [CloudFront Lambda@Edge](#cloudfront-lambdaedge)\n  - [API Gateway Lambda Authorizer - REST](#api-gateway-lambda-authorizer---rest)\n  - [HTTP API Authorizer](#http-api-lambda-authorizer)\n  - [AppSync Lambda Authorizer](#appsync-lambda-authorizer)\n  - [Fastify](#fastify)\n  - [Express](#express)\n- [Security](#security)\n- [License](#license)\n\n## Verifying JWTs from Amazon Cognito\n\nCreate a `CognitoJwtVerifier` instance and use it to verify JWTs:\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\n\n// Verifier that expects valid access tokens:\nconst verifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n});\n\ntry {\n  const payload = await verifier.verify(\n    \"eyJraWQeyJhdF9oYXNoIjoidk...\" // the JWT as string\n  );\n  console.log(\"Token is valid. Payload:\", payload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n```\n\nYou can also use `verifySync`, if you've made sure the JWK has already been cached, see further below.\n\n### `CognitoJwtVerifier` `verify` parameters\n\nExcept the User Pool ID, parameters provided when creating the `CognitoJwtVerifier` act as defaults, that can be overridden upon calling `verify` or `verifySync`.\n\nSupported parameters are:\n\n- `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`.\n- `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).\n- `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).\n- `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](#Checking-scope).\n- `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.\n- `customJwtCheck` (optional): your custom function with additional JWT (and JWK) checks to execute (see also below).\n- `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](#peek-inside-invalid-jwts).\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\n\nconst verifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\", // mandatory, can't be overridden upon calling verify\n  tokenUse: \"id\", // needs to be specified here or upon calling verify\n  clientId: \"<client_id>\", // needs to be specified here or upon calling verify\n  groups: \"admins\", // optional\n  graceSeconds: 0, // optional\n  scope: \"my-api/read\", // optional\n  customJwtCheck: (payload, header, jwk) => {}, // optional\n});\n\ntry {\n  const payload = await verifier.verify(\"eyJraWQeyJhdF9oYXNoIjoidk...\", {\n    groups: \"users\", // Cognito groups overridden: should be users (not admins)\n  });\n  console.log(\"Token is valid. Payload:\", payload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n```\n\n### Checking scope\n\nIf you provide scopes to the `CognitoJwtVerifier`, the verifier will make sure the `scope` claim in the JWT includes at least one of those scopes:\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\n\nconst verifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\", // scopes are only present on Cognito access tokens\n  clientId: \"<client_id>\",\n  scope: [\"my-api:write\", \"my-api:admin\"],\n});\n\ntry {\n  const payload = await verifier.verify(\"eyJraWQeyJhdF9oYXNoIjoidk...\");\n  console.log(\"Token is valid. Payload:\", payload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n```\n\nSo a JWT payload like the following would have a valid scope:\n\n```javascript\n{\n  \"client_id\": \"<client_id>\",\n  \"scope\": \"my-api:write someotherscope yetanotherscope\", // scope string is split on spaces to gather the array of scopes to compare with\n  \"iat\": 1234567890,\n  \"...\": \"...\"\n}\n```\n\nThis scope would not be valid:\n\n```javascript\n{\n  \"client_id\": \"<client_id>\",\n  \"scope\": \"my-api:read someotherscope yetanotherscope\", // Neither \"my-api:write\" nor \"my-api:admin\" present\n  \"iat\": 1234567890,\n  \"...\": \"...\"\n}\n```\n\n### Custom JWT and JWK checks\n\nIt'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.\n\nThe function will be called with:\n\n- the decoded JWT header\n- the decoded JWT payload\n- the JWK that was used to verify the JWT\n\nThrow an error in this function if you want to reject the JWT.\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\n\nconst idTokenVerifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"id\",\n  clientId: \"<client_id>\",\n  customJwtCheck: async ({ header, payload, jwk }) => {\n    if (header.someHeaderField !== \"expected\") {\n      throw new Error(\"something wrong with the header\");\n    }\n    if (payload.somePayloadField !== \"expected\") {\n      throw new Error(\"something wrong with the payload\");\n    }\n    if (jwk.someJwkfField !== \"expected\") {\n      throw new Error(\"something wrong with the jwk\");\n    }\n    await someAsyncCheck(...); // can call out to a DB or do whatever\n  },\n});\n\n// This will now throw, even if the JWT is otherwise valid, if your custom function throws:\nawait idTokenVerifier.verify(\"eyJraWQeyJhdF9oYXNoIjoidk...\");\n```\n\nNote that `customJwtCheck` may be an async function, but only if you use `verify` (not supported for `verifySync`).\n\n### Trusting multiple User Pools\n\nIf you want to allow JWTs from multiple User Pools, provide an array with these User Pools upon creating the verifier:\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\n\n// This verifier will trust both User Pools\nconst idTokenVerifier = CognitoJwtVerifier.create([\n  {\n    userPoolId: \"<user_pool_id>\",\n    tokenUse: \"id\",\n    clientId: \"<client_id>\", // clientId is mandatory at verifier level now, to disambiguate between User Pools\n  },\n  {\n    userPoolId: \"<user_pool_id_2>\",\n    tokenUse: \"id\",\n    clientId: \"<client_id_2>\",\n  },\n]);\n\ntry {\n  const idTokenPayload = await idTokenVerifier.verify(\n    \"eyJraWQeyJhdF9oYXNoIjoidk...\" // token must be signed by either of the User Pools\n  );\n  console.log(\"Token is valid. Payload:\", idTokenPayload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n```\n\n### Using the generic JWT RSA verifier for Cognito JWTs\n\nThe generic `JwtRsaVerifier` (see [below](#verifying-jwts-from-any-oidc-compatible-idp)) 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.\n\nIn this case, leave `audience` to `null`, but rather manually add `validateCognitoJwtFields` in the `customJwtCheck`.\n(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)\n\n```typescript\nimport { JwtRsaVerifier } from \"aws-jwt-verify\";\nimport { validateCognitoJwtFields } from \"aws-jwt-verify/cognito-verifier\";\n\nconst verifier = JwtRsaVerifier.create([\n  {\n    issuer: \"https://cognito-idp.eu-west-1.amazonaws.com/<user_pool_id>\",\n    audience: null, // audience (~clientId) is checked instead, by the Cognito specific checks below\n    customJwtCheck: ({ payload }) =>\n      validateCognitoJwtFields(payload, {\n        tokenUse: \"access\", // set to \"id\" or \"access\" (or null if both are fine)\n        clientId: \"<client_id>\", // provide the client id, or an array of client ids (or null if you do not want to check client id)\n        groups: [\"admin\", \"others\"], // optional, provide a group name, or array of group names\n      }),\n  },\n  {\n    issuer: \"https://example.com/my/other/idp\",\n    audience: \"myaudience\", // do specify audience for other IDPs\n  },\n]);\n```\n\n## Verifying JWTs from any OIDC-compatible IDP\n\nThe generic `JwtRsaVerifier` works for any OIDC-compatible IDP that signs JWTs with RS256/RS384/RS512:\n\n```typescript\nimport { JwtRsaVerifier } from \"aws-jwt-verify\";\n\nconst verifier = JwtRsaVerifier.create({\n  issuer: \"https://example.com/\", // set this to the expected \"iss\" claim on your JWTs\n  audience: \"<audience>\", // set this to the expected \"aud\" claim on your JWTs\n  jwksUri: \"https://example.com/.well-known/jwks.json\", // set this to the JWKS uri from your OpenID configuration\n});\n\ntry {\n  const payload = await verifier.verify(\"eyJraWQeyJhdF9oYXNoIjoidk...\");\n  console.log(\"Token is valid. Payload:\", payload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n```\n\nSupport Multiple IDP's:\n\n```typescript\nconst verifier = JwtRsaVerifier.create([\n  {\n    issuer: \"https://example.com/idp1\",\n    audience: \"expectedAudienceIdp1\",\n  },\n  {\n    issuer: \"https://example.com/idp2\",\n    audience: \"expectedAudienceIdp2\",\n  },\n]);\n\ntry {\n  const otherPayload = await verifier.verify(\"eyJraWQeyJhdF9oYXNoIjoidk...\"); // Token must be from either idp1 or idp2\n  console.log(\"Token is valid. Payload:\", otherPayload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n```\n\n### `JwtRsaVerifier` `verify` parameters\n\nExcept `issuer`, parameters provided when creating the `JwtRsaVerifier` act as defaults, that can be overridden upon calling `verify` or `verifySync`.\n\nSupported parameters are:\n\n- `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`.\n- `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 `JwtRsaVerifier` 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.\n- `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](#checking-scope).\n- `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.\n- `customJwtCheck` (optional): your custom function with additional JWT checks to execute (see [Custom JWT and JWK checks](#custom-jwt-and-jwk-checks)).\n- `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](#peek-inside-invalid-jwts).\n\n## Verification errors\n\nWhen verification of a JWT fails, this library will throw an error. All errors are defined in [src/error.ts](./src/error.ts) and can be imported and tested for like so:\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\nimport { JwtExpiredError } from \"aws-jwt-verify/error\";\n\nconst verifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n});\n\ntry {\n  const payload = await verifier.verify(\n    \"eyJraWQeyJhdF9oYXNoIjoidk...\" // the JWT as string\n  );\n} catch (err) {\n  // An error is thrown, so the JWT is not valid\n  // Use `instanceof` to test for specific error cases:\n  if (err instanceof JwtExpiredError) {\n    console.error(\"JWT expired!\");\n  }\n  throw err;\n}\n```\n\n### Peek inside invalid JWTs\n\nIf you want to peek inside invalid JWTs, set `includeRawJwtInErrors` to `true` when creating the verifier. The thrown error will then include the raw JWT:\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\nimport { JwtInvalidClaimError } from \"aws-jwt-verify/error\";\n\nconst verifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n  includeRawJwtInErrors: true, // can also be specified as parameter to the `verify` call\n});\n\ntry {\n  const payload = await verifier.verify(\n    \"eyJraWQeyJhdF9oYXNoIjoidk...\" // the JWT as string\n  );\n} catch (err) {\n  if (err instanceof JwtInvalidClaimError) {\n    // You can log the payload of the raw JWT, e.g. to aid in debugging and alerting on authentication errors\n    // Be careful not to disclose information on the error reason to the the client\n    console.error(\"JWT invalid because:\", err.message);\n    console.error(\"Raw JWT:\", err.rawJwt.payload);\n  }\n  throw new Error(\"Unauthorized\");\n}\n```\n\nThe `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:\n\n- Stage 1: Verify JWT structure and JSON parse the JWT\n- Stage 2: Verify JWT cryptographic signature (i.e. RS256/RS384/RS512)\n- Stage 3: Verify JWT claims (such as e.g. its expiration)\n\nOnly 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).\n\nNote that if you use [custom JWT checks](#custom-jwt-and-jwk-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:\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\nimport { JwtInvalidClaimError } from \"aws-jwt-verify/error\";\n\nclass CustomError extends JwtInvalidClaimError {}\n\nconst verifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n  includeRawJwtInErrors: true,\n  customJwtCheck: ({ payload }) => {\n    if (payload.custom_claim !== \"expected\")\n      throw new CustomError(\"Invalid JWT\", payload.custom_claim, \"expected\");\n  },\n});\n\ntry {\n  const payload = await verifier.verify(\n    \"eyJraWQeyJhdF9oYXNoIjoidk...\" // the JWT as string\n  );\n} catch (err) {\n  if (err instanceof JwtInvalidClaimError) {\n    console.error(\"JWT invalid:\", err.rawJwt.payload);\n  }\n  throw new Error(\"Unauthorized\");\n}\n```\n\n## The JWKS cache\n\nThe 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) `JwtRsaVerifier` 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).\n\nNote: examples below work the same for `CognitoJwtVerifier` and `JwtRsaVerifier`.\n\n### Loading the JWKS from file\n\nIf 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:\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\nimport { readFileSync } from \"fs\";\n\nconst idTokenVerifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"id\",\n  clientId: \"<client_id>\",\n});\n\nconst jwks = JSON.parse(readFileSync(\"jwks.json\", { encoding: \"utf-8\" }));\nidTokenVerifier.cacheJwks(jwks);\n\n// Because the JWKS doesn't need to be downloaded now, you can use verifySync:\ntry {\n  const idTokenPayload = idTokenVerifier.verifySync(\n    \"eyJraWQeyJhdF9oYXNoIjoidk...\"\n  );\n  console.log(\"Token is valid. Payload:\", payload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n\n// Async verify will of course work as well (and will use the cache also):\ntry {\n  const idTokenPayload = await idTokenVerifier.verify(\n    \"eyJraWQeyJhdF9oYXNoIjoidk...\"\n  );\n  console.log(\"Token is valid. Payload:\", idTokenPayload);\n} catch {\n  console.log(\"Token not valid!\");\n}\n```\n\nNote 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).\n\n### Rate limiting\n\nBoth the `CognitoJwtVerifier` and the `JwtRsaVerifier` 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.\n\nThe 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.\n\nThe 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).\n\nIt is possible to implement a different rate limiting scheme yourself, by customizing the JWKS cache, or the `penaltyBox` implementation, see below.\n\n### Explicitly hydrating the JWKS cache\n\nIn 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.\n\nThis 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):\n\n```typescript\nconst verifier = JwtRsaVerifier.create([\n  {\n    issuer: \"https://example.com/idp1\",\n    audience: \"myappclient1\",\n  },\n  {\n    issuer: \"https://example.com/idp2\",\n    audience: \"myappclient2\",\n  },\n]);\n\n// Fetch and cache the JWKS for all configured issuers\nawait verifier.hydrate();\n```\n\nNote: 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).\n\n### Clearing the JWKS cache\n\nIf you have a predefined rotation schedule for your JWKS, you could set the refresh interval of the verifier aligned to this schedule:\n\n```typescript\nimport { JwtRsaVerifier } from \"aws-jwt-verify\";\n\nconst verifier = JwtRsaVerifier.create({\n  issuer: \"https://example.com/\",\n  audience: \"<audience>\",\n});\n\nsetInterval(() => {\n  verifier.cacheJwks({ keys: [] }); // empty cache, by loading an empty JWKS\n}, 1000 * 60 * 60 * 4); // For a 4 hour refresh schedule\n```\n\nIf an automated rotation does not fit your use case, and you need to clear out the JWKS cache, you could use:\n\n```typescript\nverifier.cacheJwks({ keys: [] });\n```\n\n### Customizing the JWKS cache\n\nWhen you instantiate a `CognitoJwtVerifier` or `JwtRsaVerifier` without providing a `JwksCache`, the `SimpleJwksCache` is used:\n\n```typescript\nimport { JwtRsaVerifier } from \"aws-jwt-verify\";\nimport { SimpleJwksCache } from \"aws-jwt-verify/jwk\";\n\nconst verifier = JwtRsaVerifier.create({\n  issuer: \"http://my-tenant.my-idp.com\",\n});\n\n// Equivalent:\nconst verifier2 = JwtRsaVerifier.create(\n  {\n    issuer: \"http://my-tenant.my-idp.com\",\n  },\n  {\n    jwksCache: new SimpleJwksCache(),\n  }\n);\n```\n\nThe `SimpleJwksCache` can be tailored by using a different `penaltyBox` and/or `fetcher` (see below).\n\nAlternatively, 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.\n\n### Sharing the JWKS cache amongst different verifiers\n\nIf 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:\n\n```typescript\nimport { JwtRsaVerifier } from \"aws-jwt-verify\";\nimport { SimpleJwksCache } from \"aws-jwt-verify/jwk\";\n\nconst sharedJwksCache = new SimpleJwksCache();\n\nconst verifierA = JwtRsaVerifier.create(\n  {\n    jwksUri: \"https://example.com/keys/jwks.json\",\n    issuer: \"https://example.com/\",\n    audience: \"<audience>\",\n  },\n  {\n    jwksCache: sharedJwksCache,\n  }\n);\n\nconst verifierB = JwtRsaVerifier.create(\n  {\n    jwksUri: \"https://example.com/keys/jwks.json\", // same JWKS URI, so sharing cache makes sense\n    issuer: \"https://example.com/\",\n    audience: \"<audience>\",\n  },\n  {\n    jwksCache: sharedJwksCache,\n  }\n);\n```\n\n### Using a different `JsonFetcher` with `SimpleJwksCache`\n\nWhen instantiating `SimpleJwksCache`, the `fetcher` property can be populated with an instance of a class that implements the interface `JsonFetcher` (from `\"aws-jwt-verify/https\"`), such as the `SimpleJsonFetcher` (which is the default).\n\nThe purpose of the fetcher, is to execute fetches against the JWKS uri (HTTPS GET) and parse the resulting JSON file.\nThe default implementation, the `SimpleJsonFetcher`, has basic machinery to do fetches over HTTPS. It does 1 (immediate) retry in case of connection errors.\n\nBy supplying a custom fetcher when instantiating `SimpleJwksCache`, instead of `SimpleJsonFetcher`, you can implement any retry and backoff scheme you want, or use another HTTPS library:\n\n```typescript\nimport { JwtRsaVerifier } from \"aws-jwt-verify\";\nimport { SimpleJwksCache } from \"aws-jwt-verify/jwk\";\nimport { JsonFetcher } from \"aws-jwt-verify/https\";\nimport axios from \"axios\";\n\n// Use axios to do the HTTPS fetches\nclass CustomFetcher implements JsonFetcher {\n  instance = axios.create();\n  public async fetch(uri: string) {\n    return this.instance.get(uri).then((response) => response.data);\n  }\n}\n\nconst verifier = JwtRsaVerifier.create(\n  {\n    issuer: \"http://my-tenant.my-idp.com\",\n  },\n  {\n    jwksCache: new SimpleJwksCache({\n      fetcher: new CustomFetcher(),\n    }),\n  }\n);\n```\n\n### Configuring the JWKS response timeout and other HTTP options with `JsonFetcher`\n\nThe following configurations are equivalent, use the latter one to set a custom fetch timeout and other HTTP options.\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\n\n// No jwksCache configured explicitly,\n// so the default `SimpleJwksCache` with `SimpleJsonFetcher` will be used,\n// with a default response timeout of 1500 ms.:\nconst verifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\", // or \"id\"\n  clientId: \"<client_id>\",\n});\n```\n\nEquivalent explicit configuration:\n\n```typescript\nimport { CognitoJwtVerifier } from \"aws-jwt-verify\";\nimport { SimpleJwksCache } from \"aws-jwt-verify/jwk\";\nimport { SimpleJsonFetcher } from \"aws-jwt-verify/https\";\n\nconst verifier = CognitoJwtVerifier.create(\n  {\n    userPoolId: \"<your user pool id>\",\n    tokenUse: \"access\", // or \"id\",\n    clientId: \"<your client id>\",\n  },\n  {\n    jwksCache: new SimpleJwksCache({\n      fetcher: new SimpleJsonFetcher({\n        defaultRequestOptions: {\n          responseTimeout: 1500,\n          // You can add additional request options:\n          // For NodeJS: https://nodejs.org/api/http.html#httprequestoptions-callback\n          // For Web (init object): https://developer.mozilla.org/en-US/docs/Web/API/fetch#syntax\n        },\n      }),\n    }),\n  }\n);\n```\n\n### Using a different `penaltyBox` with `SimpleJwksCache`\n\nWhen 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).\n\nThe `SimpleJwksCache` will always do `await penaltyBox.wait(jwksUri, kid)` before asking the `fetcher` to fetch the JWKS.\n\nBy 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.\n\nThe `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.\n\n```typescript\nimport { JwtRsaVerifier } from \"aws-jwt-verify\";\nimport {\n  SimpleJwksCache,\n  SimplePenaltyBox,\n  PenaltyBox,\n} from \"aws-jwt-verify/jwk\";\n\n// In this example we use the SimplePenaltyBox, but override the default wait period\nconst verifier = JwtRsaVerifier.create(\n  {\n    issuer: \"http://my-tenant.my-idp.com\",\n  },\n  {\n    jwksCache: new SimpleJwksCache({\n      penaltyBox: new SimplePenaltyBox({ waitSeconds: 1 }),\n    }),\n  }\n);\n\n// Or implement your own penaltyBox\n// The example here just stupidly waits 5 second always,\n// even on the first fetch of the JWKS uri\nclass CustomPenaltyBox implements PenaltyBox {\n  public async wait(jwksUri: string, kid: string) {\n    // implement something better\n    await new Promise((resolve) => setTimeout(resolve, 5000));\n  }\n  public registerFailedAttempt(jwksUri: string, kid: string) {\n    // implement\n  }\n  public registerSuccessfulAttempt(jwksUri: string, kid: string) {\n    // implement\n  }\n}\nconst verifier2 = JwtRsaVerifier.create(\n  {\n    issuer: \"http://my-tenant.my-idp.com\",\n  },\n  {\n    jwksCache: new SimpleJwksCache({ penaltyBox: new CustomPenaltyBox() }),\n  }\n);\n```\n\n## Usage Examples\n\n### CloudFront Lambda@Edge\n\nThe 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\".\n\nThis is an example of a [Viewer Request Lambda@Edge](https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html) 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.\n\n```javascript\nconst { CognitoJwtVerifier } = require(\"aws-jwt-verify\");\n\n// Create the verifier outside the Lambda handler (= during cold start),\n// so the cache can be reused for subsequent invocations. Then, only during the\n// first invocation, will the verifier actually need to fetch the JWKS.\nconst jwtVerifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n  scope: \"read\",\n});\n\nexports.handler = async (event) => {\n  const { request } = event.Records[0].cf;\n  const accessToken = request.headers[\"authorization\"][0].value;\n  try {\n    await jwtVerifier.verify(accessToken);\n  } catch {\n    return {\n      status: \"403\",\n      body: \"Unauthorized\",\n    };\n  }\n  return request; // allow request to proceed\n};\n```\n\n### API Gateway Lambda Authorizer - REST\n\nThe 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\".\n\nTwo 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](https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/blob/master/blueprints/nodejs/index.js) as a reference pattern where the [token validation](https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/blob/master/blueprints/nodejs/index.js#L17) could be achieved as follows\n\nFor token based authorizers, where lambda event payload is set to `Token` and token source is set to (http) `Header` with name `authorization`:\n\n```javascript\nconst { CognitoJwtVerifier } = require(\"aws-jwt-verify\");\n\n// Create the verifier outside the Lambda handler (= during cold start),\n// so the cache can be reused for subsequent invocations. Then, only during the\n// first invocation, will the verifier actually need to fetch the JWKS.\nconst jwtVerifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n  scope: \"read\",\n});\n\nexports.handler = async (event) => {\n  const accessToken = event.authorizationToken;\n\n  let payload;\n  try {\n    // If the token is not valid, an error is thrown:\n    payload = await jwtVerifier.verify(accessToken);\n  } catch {\n    // API Gateway wants this *exact* error message, otherwise it returns 500 instead of 401:\n    throw new Error(\"Unauthorized\");\n  }\n\n  // Proceed with additional authorization logic\n  // ...\n};\n```\n\nFor request based authorizers, where lambda event payload is set to `Request` and identity source is set to (http) `Header` with name `authorization`:\n\n```javascript\nconst { CognitoJwtVerifier } = require(\"aws-jwt-verify\");\n\n// Create the verifier outside the Lambda handler (= during cold start),\n// so the cache can be reused for subsequent invocations. Then, only during the\n// first invocation, will the verifier actually need to fetch the JWKS.\nconst jwtVerifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n  scope: \"read\",\n});\n\nexports.handler = async (event) => {\n  const accessToken = event.headers[\"authorization\"];\n\n  let payload;\n  try {\n    // If the token is not valid, an error is thrown:\n    payload = await jwtVerifier.verify(accessToken);\n  } catch {\n    // API Gateway wants this *exact* error message, otherwise it returns 500 instead of 401:\n    throw new Error(\"Unauthorized\");\n  }\n\n  // Proceed with additional authorization logic\n  // ...\n};\n```\n\n### HTTP API Lambda Authorizer\n\nAn example of a sample HTTP Lambda authorizer is included [here](tests/cognito/lib/lambda-authorizer/index.js) as part of the test suite for the solution ([format 2.0](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-lambda-authorizer.html#http-api-lambda-authorizer.payload-format-response)).\n\n### AppSync Lambda Authorizer\n\nThe 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\".\n\nThis is an example of [AppSync Lambda Authorization](https://docs.aws.amazon.com/appsync/latest/devguide/security-authz.html#aws-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\n\n```javascript\nconst { CognitoJwtVerifier } = require(\"aws-jwt-verify\");\n\n// Create the verifier outside the Lambda handler (= during cold start),\n// so the cache can be reused for subsequent invocations. Then, only during the\n// first invocation, will the verifier actually need to fetch the JWKS.\nconst jwtVerifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n  scope: \"read\",\n});\n\nexports.handler = async (event) => {\n  const accessToken = event.authorizationToken;\n  try {\n    await jwtVerifier.verify(accessToken);\n  } catch {\n    return {\n      isAuthorized: false,\n    };\n  }\n  //Proceed with additional authorization logic\n};\n```\n\n### Fastify\n\n```javascript\nconst { CognitoJwtVerifier } = require(\"aws-jwt-verify\");\nconst fastify = require(\"fastify\")({ logger: true });\n\n// Create the verifier outside your route handlers,\n// so the cache is persisted and can be shared amongst them.\nconst jwtVerifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n  scope: \"read\",\n});\n\nfastify.get(\"/\", async (request, reply) => {\n  try {\n    // A valid JWT is expected in the HTTP header \"authorization\"\n    await jwtVerifier.verify(request.headers.authorization);\n  } catch (authErr) {\n    fastify.log.error(authErr);\n    const err = new Error();\n    err.statusCode = 403;\n    throw err;\n  }\n  return { private: \"only visible to users sending a valid JWT\" };\n});\n\nconst startFastify = async () => {\n  try {\n    await fastify.listen(3000);\n  } catch (err) {\n    fastify.log.error(err);\n    process.exit(1);\n  }\n};\n\n// Hydrate the JWT verifier, and start Fastify.\n// Hydrating the verifier makes sure the JWKS is loaded into the JWT verifier,\n// so it can verify JWTs immediately without any latency.\n// (Alternatively, just start Fastify, the JWKS will be downloaded when the first JWT is being verified then)\nPromise.all([jwtVerifier.hydrate(), () => fastify.listen(3000)]).catch(\n  (err) => {\n    fastify.log.error(err);\n    process.exit(1);\n  }\n);\n```\n\n### Express\n\n```javascript\nconst { CognitoJwtVerifier } = require(\"aws-jwt-verify\");\nconst express = require(\"express\");\nconst app = express();\nconst port = 3000;\n\n// Create the verifier outside your route handlers,\n// so the cache is persisted and can be shared amongst them.\nconst jwtVerifier = CognitoJwtVerifier.create({\n  userPoolId: \"<user_pool_id>\",\n  tokenUse: \"access\",\n  clientId: \"<client_id>\",\n  scope: \"read\",\n});\n\napp.get(\"/\", async (req, res, next) => {\n  try {\n    // A valid JWT is expected in the HTTP header \"authorization\"\n    await jwtVerifier.verify(req.header(\"authorization\"));\n  } catch (err) {\n    console.error(err);\n    return res.status(403).json({ statusCode: 403, message: \"Forbidden\" });\n  }\n  res.json({ private: \"only visible to users sending a valid JWT\" });\n});\n\n// Hydrate the JWT verifier, then start express.\n// Hydrating the verifier makes sure the JWKS is loaded into the JWT verifier,\n// so it can verify JWTs immediately without any latency.\n// (Alternatively, just start express, the JWKS will be downloaded when the first JWT is being verified then)\njwtVerifier\n  .hydrate()\n  .catch((err) => {\n    console.error(`Failed to hydrate JWT verifier: ${err}`);\n    process.exit(1);\n  })\n  .then(() =>\n    app.listen(port, () => {\n      console.log(`Example app listening at http://localhost:${port}`);\n    })\n  );\n```\n\n# Security\n\nSee [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.\n\n# License\n\nThis project is licensed under the Apache-2.0 License.\n","readmeFilename":"README.md"}