欧博官网How to decode JWT token with JWK in Python

I know that this is long ago answered, but this may be useful to somebody.

If you are working against an OAuth provider that supports OpenID, you can use something like the following which does the following:

Decodes the token without validation to get the issuer

Retrieves the JWKs from the OpenID configuration

Retrieves the key ID and algorithm from the token header

Decodes and validates the token

from os import environ import json import urllib.request import jwt; def get_jwks_url(issuer_url): well_known_url = issuer_url + "/.well-known/openid-configuration" with urllib.request.urlopen(well_known_url) as response: well_known = json.load(response) if not 'jwks_uri' in well_known: raise Exception('jwks_uri not found in OpenID configuration') return well_known['jwks_uri'] def decode_and_validate_token(token): unvalidated = jwt.decode(token, options={"verify_signature": False}) jwks_url = get_jwks_url(unvalidated['iss']) jwks_client = jwt.PyJWKClient(jwks_url) header = jwt.get_unverified_header(token) key = jwks_client.get_signing_key(header["kid"]).key return jwt.decode(token, key, [header["alg"]]) token = "xxxyyyzzz" decoded = decode_and_validate_token(token) print(decoded)

2025-10-15 11:36 点击量:1