Decode and verify the signature of a Cognito JSON Web Token (2024)

I want to use an Amazon Cognito user pool as the authentication method for my application. What is a secure way to verify the ID and access tokens sent by clients to my application?

Short description

When clients authenticate to your application with a user pool, Amazon Cognito sends an ID token. You can manually verify the ID token in scenarios similar to the following:

  • You created a web application and want to use an Amazon Cognito user pool for authentication.
  • You use an Amazon Cognito user pool for authentication and an Amazon Cognito identity pool to retrieve AWS Security Token Service (AWS STS) temporary credentials. AWS Lambda is invoked with those credentials, but Lambda doesn't have information about who originally authenticated with the user pool.

To get Amazon Cognito user details contained in an Amazon Cognito JSON Web Token (JWT), you can decode the token and then verify the signature.

Resolution

AWS released the following library that you can use to verify JWTs: https://github.com/awslabs/aws-jwt-verify

import { CognitoJwtVerifier } from "aws-jwt-verify";// Verifier that expects valid access tokens:const verifier = CognitoJwtVerifier.create({ userPoolId: "<user_pool_id>", tokenUse: "access", clientId: "<client_id>",});try { const payload = await verifier.verify( "eyJraWQeyJhdF9oYXNoIjoidk..." // the JWT as string ); console.log("Token is valid. Payload:", payload);} catch { console.log("Token not valid!");}

After a user logs in, an Amazon Cognito user pool returns a JWT. The JWT is a base64url-encoded JSON string ("claims") that contains information about the user. Amazon Cognito returns three tokens: the ID token, the access token, and the refresh token. The ID token contains the user fields defined in the Amazon Cognito user pool.

Tokens include three sections: a header, a payload, and a signature.

The following is the header of a sample ID token. The header contains the key ID ("kid"), as well as the algorithm ("alg") used to sign the token. In this example, the algorithm is "RS256", which is an RSA signature with SHA-256.

{ "kid": "abcdefghijklmnopqrsexample=", "alg": "RS256"}

The following is an example of the payload, which has information about the user, as well as timestamps of the token creation and expiration:

{ "sub": "aaaaaaaa-bbbb-cccc-dddd-example", "aud": "xxxxxxxxxxxxexample", "email_verified": true, "token_use": "id", "auth_time": 1500009400, "iss": "https://cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-2_example", "cognito:username": "anaya", "exp": 1500013000, "given_name": "Anaya", "iat": 1500009400, "email": "[email protected]"}

The last section is the signature, which is a hashed and encrypted combination of the header and the payload.

Amazon Cognito generates two RSA key pairs for each user pool. The private key of each pair is used to sign the respective ID token or access token. The public keys are made available at an address in the following format:

https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json

The JSON file (jwks.json) is structured in the following format:

{ "keys": [{ "alg": "RS256", "e": "AQAB", "kid": "abcdefghijklmnopqrsexample=", "kty": "RSA", "n": "lsjhglskjhgslkjgh43lj5h34lkjh34lkjht3example", "use": "sig" }, { "alg": "RS256", "e": "AQAB", "kid": "fgjhlkhjlkhexample=", "kty": "RSA", "n": "sgjhlk6jp98ugp98up34hpexample", "use": "sig" }]}

To verify the signature of an Amazon Cognito JWT, first search for the public key with a key ID that matches the key ID in the header of the token. Then, you can use libraries, such as aws-jwt-verify or those recommended by jwt.io or OpenID Foundation, to validate the signature of the token and extract values, such as expiration and user name.

Apart from the signature, it's also a best practice to verify the following:

  • The token isn't expired.
  • The audience ("aud") specified in the payload matches the app client ID created in the Amazon Cognito user pool.

The aws-jwt-verify library includes these checks on your behalf. For more code examples on how to decode and verify an Amazon Cognito JWT using Lambda, see Decode and verify Amazon Cognito JWT tokens.

Related information

Verifying a JSON Web Token

Using tokens with user pools

Decode and verify the signature of a Cognito JSON Web Token (2024)
Top Articles
Fee for ending Auction listing early
Does a VPN Affect Your Ping When You're Gaming Online
The Tribes and Castes of the Central Provinces of India, Volume 3
Skigebiet Portillo - Skiurlaub - Skifahren - Testberichte
Golden Abyss - Chapter 5 - Lunar_Angel
Exclusive: Baby Alien Fan Bus Leaked - Get the Inside Scoop! - Nick Lachey
Truist Bank Near Here
Sandrail Options and Accessories
Fort Carson Cif Phone Number
My Boyfriend Has No Money And I Pay For Everything
Top Financial Advisors in the U.S.
The Best Classes in WoW War Within - Best Class in 11.0.2 | Dving Guides
Noaa Swell Forecast
Draconic Treatise On Mining
Southland Goldendoodles
Catsweb Tx State
Tiraj Bòlèt Florida Soir
Med First James City
Red Tomatoes Farmers Market Menu
065106619
Bj Alex Mangabuddy
Tygodnik Polityka - Polityka.pl
Catherine Christiane Cruz
6 Most Trusted Pheromone perfumes of 2024 for Winning Over Women
Hannah Palmer Listal
What Individuals Need to Know When Raising Money for a Charitable Cause
27 Modern Dining Room Ideas You'll Want to Try ASAP
Democrat And Chronicle Obituaries For This Week
Tom Thumb Direct2Hr
Lilpeachbutt69 Stephanie Chavez
1964 Impala For Sale Craigslist
N.J. Hogenkamp Sons Funeral Home | Saint Henry, Ohio
Bridgestone Tire Dealer Near Me
Ixl Lausd Northwest
Joplin Pets Craigslist
Orangetheory Northville Michigan
Cross-Border Share Swaps Made Easier Through Amendments to India’s Foreign Exchange Regulations - Transatlantic Law International
Restored Republic December 9 2022
How To Paint Dinos In Ark
Pp503063
Yogu Cheshire
Danielle Ranslow Obituary
BCLJ July 19 2019 HTML Shawn Day Andrea Day Butler Pa Divorce
Greatpeople.me Login Schedule
Jackerman Mothers Warmth Part 3
Lesson 5 Homework 4.5 Answer Key
Enter The Gungeon Gunther
Bellelement.com Review: Real Store or A Scam? Read This
Barber Gym Quantico Hours
Every Type of Sentinel in the Marvel Universe
Latest Posts
Article information

Author: Prof. Nancy Dach

Last Updated:

Views: 6413

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Prof. Nancy Dach

Birthday: 1993-08-23

Address: 569 Waelchi Ports, South Blainebury, LA 11589

Phone: +9958996486049

Job: Sales Manager

Hobby: Web surfing, Scuba diving, Mountaineering, Writing, Sailing, Dance, Blacksmithing

Introduction: My name is Prof. Nancy Dach, I am a lively, joyous, courageous, lovely, tender, charming, open person who loves writing and wants to share my knowledge and understanding with you.