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
i am reading the repository
despite not using group features the code helped me for validating tokens. thanks a lot