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 年前1379 查看次数
1 回答
1
已接受的回答

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.

profile picture
专家
已回答 1 年前
profile picture
专家
已审核 2 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则