Skip to content

Instantly share code, notes, and snippets.

@jgontrum
Created August 29, 2019 12:21
Show Gist options
  • Save jgontrum/be8148462003590e5a46db76688e3f30 to your computer and use it in GitHub Desktop.
Save jgontrum/be8148462003590e5a46db76688e3f30 to your computer and use it in GitHub Desktop.
JWT & FastAPI
import os
from typing import Dict, List, Optional
import requests
from jose import jwt, jwk
from jose.utils import base64url_decode
JWK = Dict[str, str]
JWKS = Dict[str, List[JWK]]
def get_jwks() -> JWKS:
return requests.get(
f"https://cognito-idp.{os.environ.get('COGNITO_REGION')}.amazonaws.com/"
f"{os.environ.get('COGNITO_POOL_ID')}/.well-known/jwks.json"
).json()
def get_hmac_key(token: str, jwks: JWKS) -> Optional[JWK]:
kid = jwt.get_unverified_header(token).get("kid")
for key in jwks.get("keys", []):
if key.get("kid") == kid:
return key
def verify_jwt(token: str, jwks: JWKS) -> bool:
hmac_key = get_hmac_key(token, jwks)
if not hmac_key:
raise ValueError("No pubic key found!")
hmac_key = jwk.construct(get_hmac_key(token, jwks))
message, encoded_signature = token.rsplit(".", 1)
decoded_signature = base64url_decode(encoded_signature.encode())
return hmac_key.verify(message.encode(), decoded_signature)
jwks = get_jwks() # Store those once at startup time
# ...
if not verify_jwt(token, jwks):
print("You are not verified!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment