cognito-jwt-lite
v1.0.2
Published
Lightweight AWS Cognito JWT verifier
Downloads
236
Maintainers
Readme
cognito-jwt-lite
Lightweight library to verify AWS Cognito JSON Web Tokens.
This package is implemented in typescript and provide its own type definitions.
Need lightweight lib to verify Azure AD tokens ? Check this out
Getting started
Install the package using yarn or NPM: npm i cognito-jwt-lite
Do not forget to install dependent types definitions as dev dependency if you are using Typescript: npm i -D @types/jsonwebtoken @types/jwk-to-pem
.
In your authentication middleware decode and verify the token using:
import { verify } from 'cognito-jwt-lite';
const decoded = await verify(token, {
issuer: `https://cognito-idp.${process.env.AWS_COGNITO_POOL_REGION}.amazonaws.com/${process.env.AWS_COGNITO_POOL_ID}`,
});
You can add any option supported by jsonwebtoken:
import { verify } from 'cognito-jwt-lite';
const decoded = await verify(token, {
audience: process.env.JWT_AUD,
issuer: `https://cognito-idp.${process.env.AWS_COGNITO_POOL_REGION}.amazonaws.com/${process.env.AWS_COGNITO_POOL_ID}`,
});
Additional options
- Retries on 5xx: set the number of retries when request to fetch keys returns a 5xx response (defaults to 2)
import { verify } from 'cognito-jwt-lite';
const decoded = await verify(token, {
maxRetries: 5,
audience: process.env.JWT_AUD,
issuer: process.env.JWT_ISS,
});
Error reference
The lib will throw the following errors if something wrong happends during decoding token:
InvalidToken
: the token provided is not a non-empty string.InvalidIssuer
: the issuer does not match the patternhttps://cognito-idp.<aws-region>.amazonaws.com/<pool-id>
TokenNotDecoded
: the token cannot be decoded. This usually means the token is ill-formed.MissingKeyID
: nokid
(Key ID) field is present in JWT header.ErrorFetchingKeys
: API call to fetch Cognito public keys failed.NotMatchingKey
: no matching key is found in Cognito response.JsonWebTokenError
: token cannot be verified, the human-readable reason is provided (expired, audience mismatch etc...)