Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Cognito What is the way to verify the ID and access tokens sent by clients to my application

I have created a user pool in cognito and after login to my application, I store the three tokens generated from AWS Cognito in session.

I need to pass these tokens to a third party API and they will in return send me the response along with the token that was sent.

How do I validate token with just user pool ID and client App Id.

like image 398
Pooja Avatar asked Jan 24 '26 20:01

Pooja


1 Answers

This AWS Blog post explains the solution in detail.

The ID Token and Access Token generated by Amazon Cognito are JWTs. Cognito uses two RSA key pairs to generate these tokens. The private key of each pair is used to sign the tokens. The public keys can be used to verify the tokens. These public keys are available at

https://cognito-idp.{REGION}.amazonaws.com/{YOUR_USER_POOL_ID}/.well-known/jwks.json

Using the Key ID from this path, you need to get the public key. Using this public key, you can verify the tokens.

Following is a NodeJS code snippet to implement the above logic. Complete example can be seen at this commit

const jwt = require('jsonwebtoken'); // JS Lib used to verify JWTs
const jwksClient = require('jwks-rsa'); // JS Lib to get keys from a URL
const USER_POOL_ID = "<YOUR_USER_POOL_ID>";
const CLIENT_ID = "<YOUR_CLIENT_ID>";
const REGION = "<YOUR_REGION>";
const ISSUER_URI = "https://cognito-idp." + REGION + ".amazonaws.com/" + USER_POOL_ID;
const JWKS_URI = ISSUER_URI + "/.well-known/jwks.json";

// Generate a client to read keys from the Cognito public URL
let client = jwksClient({
    jwksUri: JWKS_URI,
});

// Async function to get public keys from key Id in jwks.json
function getKey(header, callback) {
    client.getSigningKey(header.kid, (err, key) => {
        var signingKey = key.publicKey || key.rsaPublicKey;
        callback(null, signingKey);
    });
}

// Verify jwt. getKey function will take the header from your idToken and get 
the corresponding public key. This public key will be used by jwt.verify() to 
actually verify the token.

jwt.verify(idToken, getKey, { audience: CLIENT_ID, issuer: ISSUER_URI }, function(err, decoded) {
   console.log("RES", err, decoded); 
   // Additional verifications like token expiry can be done here.
}
like image 128
Sarthak Jain Avatar answered Jan 26 '26 23:01

Sarthak Jain