Validate a AWS Cognito JWT token

In this post we will provide an example on how to validate a AWS cognito JWT token.

Setup:

You will need to add the following dependancies to your project:

Validate a AWS cognito JWT token:

AWS cognito tokens are signed by a private key, the public key is normally available via the user pool i.e https://cognito-idp.us-east-1.amazonaws.com/<userpoolID>.

You will first need to implement the RSAKeyProvider interface

NOTE: The cognitoUrl is referring to your cognitoPool url. And the KeyId is what is specified in the JWT token header under kid property.

Now we need a service, to parse the JWT token and check the token is singed by the key specified in the JWT token header (The JWT token has a kid attribute in the header which should match a kid returned from the cognitoPool link).

You will inject your AwsCognitoRSAKeyProvider object into the CognitoJwtTokenUnpackService. If the token is not signed by the specified key in the header then an exception will be thrown. An exception will also be thrown if the token has expired. Once you have verified the token is valid then you can extract elements from the JWT token payload via the claims.get() method.

In summary, I hope this post has helped you validate a JWT token.

Similar posts:

  1. Get file from AWS S3 bucket
  2. List files in a AWS S3 Bucket
  3. Create a bucket on S3
  4. Delete a bucket on S3

References:

  1. Online JWT parser and validator
  2. AWS Cognito JWT documentation

Leave a Reply