I am trying to verify a JWT token using a JWKS URL from Ping Identity in Python. Below is the implementation:
import jwt
import requests
from jwt.algorithms import RSAAlgorithm
# JWKS URL (Replace with Ping Identity's URL)
JWKS_URL = "https://your-ping-identity-domain/.well-known/jwks.json"
# JWT Token to Verify
token = "your_jwt_token_here"
# Fetch JWKS
response = requests.get(JWKS_URL)
jwks = response.json()
# Extract Key
def get_public_key(kid):
for key in jwks["keys"]:
if key["kid"] == kid:
return RSAAlgorithm.from_jwk(key)
raise ValueError("Public key not found")
# Decode JWT Header
header = jwt.get_unverified_header(token)
kid = header["kid"]
# Get Matching Public Key
public_key = get_public_key(kid)
# Verify JWT
try:
decoded_token = jwt.decode(token, public_key, algorithms=["RS256"], audience="your_audience", issuer="your_issuer")
print("JWT is valid:", decoded_token)
except jwt.ExpiredSignatureError:
print("JWT has expired")
except jwt.InvalidTokenError:
print("Invalid JWT")