Reputation: 21
I am using AWS Cognito for my user management. When I sign in, I can get AccessToken, RefreshToken, and IdToken from AWS. The official AWS Documentation says that IdToken contains personal information like user's email address. So once I sign in, I am gonna build an express middleware that protects the route using IdToken. So the front end sends requests including the IdToken. The back end gets the IdToken, decodes it and gets the user's email address and verifies it to protect the route. This is the code for that:
const jwt = require('jsonwebtoken')
const jwtToPem = require('jwk-to-pem')
const { idToken } = req.body
const pem = jwtToPem(jwk)
jwt.verify(idToken, pem, { algorithms: ['RS256'] }, function(err, decodedToken) {
console.log("decoded Token : ", decodedToken)
});
But in that code above I still don't have JWK (JSON Web Key). I searched for JWK but didn't get the proper answer on how to get it. So my question is how can I JWK for my Cognito user pool?
This is what chatGPT answered me.
To get the JSON Web Key (JWK) for your Cognito user pool in AWS, you can retrieve it from the JWKS (JSON Web Key Set) URI of your user pool. The JWKS URI contains public information about the private key that signed your user's token. You can find the JWKS URI for your user pool at `https://cognito-idp.<Region>.amazonaws.com/<userPoolId>/.well-known/jwks.json`[1]. Here's a summary of the steps to retrieve the JWK:
1. Construct the JWKS URI for your environment: `https://cognito-idp.<Region>.amazonaws.com/<userPoolId>/.well-known/jwks.json`.
2. Retrieve the JWK from the JWKS URI for your user pool.
But I still cannot get the JWK
Upvotes: 2
Views: 999
Reputation: 44958
You can get this by simply using this URL https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json
. Just replace the region with the region in which your Cognito user pool is and replace the id with the identifier of the user pool.
I've usually used https://jwt.davetonge.co.uk/ to debug the JWT verification. You can plug in the encoded JWT and the JWKS URL.
Rather than manually fetching the keys from the JWKS, I suggest using a library. https://github.com/ghdna/cognito-express/blob/master/lib/strategy.js
Upvotes: 1