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
질문됨 일 년 전1350회 조회
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
전문가
답변함 일 년 전
profile picture
전문가
검토됨 2달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠