Created
May 19, 2021 17:36
-
-
Save mike-pete/ace87f99fb1482461ce287dcb8f18612 to your computer and use it in GitHub Desktop.
AWS Cognito JWT Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://renzolucioni.com/verifying-jwts-with-jwks-and-pyjwt/ | |
import jwt | |
import json | |
import urllib.request | |
# config | |
region = '' | |
userpoolID = '' | |
appClientID = '' | |
token = '' | |
# get kid from token | |
kid = jwt.get_unverified_header(token)['kid'] | |
key = False | |
# fetch public jwk info | |
keys_url = f'https://cognito-idp.{region}.amazonaws.com/{userpoolID}/.well-known/jwks.json' | |
with urllib.request.urlopen(keys_url) as f: | |
response = f.read() | |
jwks = json.loads(response.decode('utf-8'))['keys'] | |
for jwk in jwks: | |
if (jwk['kid'] == kid): | |
key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk)) | |
break | |
if key: | |
payload = jwt.decode(token, key=key, audience=appClientID, algorithms=['RS256']) | |
print(payload) | |
else: | |
print('##ERROR (JWT AUTH): kid not found! Check your config fields.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment