Skip to content

aws cognito verifying jwt token

0

i am using cognito for my lambda api. i wrote a login page and after logged in created a jwt_token in browser's cookie. after authentication in my main lambda i read the jwt_token from cookie but i can't verify it with python. chatgpt wrote me a verifying code but it doesn't work. because there is no x5c in my jwk key. how can i hande this? the code that chatgpt suggested is: import jwt import requests from cryptography.x509 import load_pem_x509_certificate from cryptography.hazmat.backends import default_backend

def verify_jwt_token(jwt_token, user_pool_id, region): # Get the JWKS URL jwks_url = f'https://cognito-idp.{region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json'

# Make a GET request to the JWKS URL
response = requests.get(jwks_url)
jwks = response.json()

# Extract the key ID (kid) from the JWT token header
jwt_header = jwt.get_unverified_header(jwt_token)
kid = jwt_header['kid']

# Find the key with a matching kid in the JWKS keys
keys = jwks['keys']
for key in keys:
    if key['kid'] == kid:
        cert = key.get('x5c')
        if cert:
            # Extract the public key from the JWKS key
            public_key = load_pem_x509_certificate(cert[0].encode('utf-8'), default_backend()).public_key()

            try:
                # Verify the JWT token using the extracted public key
                decoded_token = jwt.decode(jwt_token, public_key, algorithms=['RS256'])
                # Perform additional checks if required
                # Return True if the token is valid
                return True
            except jwt.InvalidTokenError:
                # Handle invalid tokens
                return False

# If no matching key is found, return False
return False
1 Answer
1
Accepted Answer

Hi,

On the following AWS Samples GitHub repository you can find an example that validates the JWT using the Cognito public key from the well-known/jwks.json file. I have used it this week with the a HTTPOnly cookie and it has worked perfectly. (Note that you will have to adapt the example to read the JWT from the cookie)

Hope this can help you.

EXPERT
answered 3 years ago
EXPERT
reviewed 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.