Python JWT Validation Example
⚠️ Important Notice: This is a basic example for demonstration purposes only. For production use, please research and implement best practices specific to your software stack, security requirements, and deployment environment. Always follow your organization's security guidelines and consider using established JWT libraries and frameworks.
📝 Note: This example demonstrates JWKS downloading and file caching for educational purposes. In production environments, you may choose to implement JWKS key management differently based on your infrastructure - such as using configuration management, environment variables, or your preferred caching strategy.
This example demonstrates how to validate Rokt JWT tokens using Python.
Prerequisites
Install the required packages:
pip install PyJWT cryptography
Complete Example
import jwt
import json
import base64
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers, SECP256R1
from cryptography.hazmat.backends import default_backend
from datetime import datetime
def load_jwk_public_key(jwk):
"""Convert JWK to ECDSA public key"""
# Decode base64url encoded coordinates
x = int.from_bytes(base64.urlsafe_b64decode(jwk['x'] + '=='), 'big')
y = int.from_bytes(base64.urlsafe_b64decode(jwk['y'] + '=='), 'big')
# Create ECDSA public key
public_numbers = EllipticCurvePublicNumbers(x, y, SECP256R1())
return public_numbers.public_key(default_backend())
def validate_jwt_token(token, jwks_json):
"""Validate JWT token using JWKS"""
try:
# Parse JWKS
jwks = json.loads(jwks_json)
if not jwks.get('keys'):
raise ValueError('No keys found in JWKS')
# Get the first key
jwk = jwks['keys'][0]
# Convert JWK to public key
public_key = load_jwk_public_key(jwk)
# Verify and decode JWT token
claims = jwt.decode(
token,
public_key,
algorithms=['ES256'],
options={'verify_exp': False} # Disable expiration check for demo - using sample token
)
return {
'is_valid': True,
'claims': claims
}
except Exception as e:
return {
'is_valid': False,
'error': str(e)
}
def main():
# Copy the test token from the Overview page
sample_token = "PASTE_TEST_TOKEN_HERE"
# JWKS endpoint URL
jwks_url = "https://public-api.rokt.com/.well-known/jwks.json"
print("=== Python JWT Validator ===")
print(f"Token: {sample_token[:50]}...")
print(f"JWKS URL: {jwks_url}")
print()
# Download and cache JWKS
import requests
import json
import os
from datetime import datetime, timedelta
jwks_cache_file = "jwks_cache.json"
# Check if cache file exists and is recent (less than 1 hour old)
if os.path.exists(jwks_cache_file):
file_age = datetime.now() - datetime.fromtimestamp(os.path.getmtime(jwks_cache_file))
if file_age < timedelta(hours=1):
print(f"Using cached JWKS from: {jwks_cache_file}")
with open(jwks_cache_file, 'r') as f:
jwks_json = f.read()
else:
print("Cache expired, downloading fresh JWKS")
response = requests.get(jwks_url, timeout=10)
response.raise_for_status()
jwks_json = response.text
# Cache the JWKS
with open(jwks_cache_file, 'w') as f:
f.write(jwks_json)
print(f"JWKS cached to: {jwks_cache_file}")
else:
print("No cache found, downloading JWKS")
response = requests.get(jwks_url, timeout=10)
response.raise_for_status()
jwks_json = response.text
# Cache the JWKS
with open(jwks_cache_file, 'w') as f:
f.write(jwks_json)
print(f"JWKS cached to: {jwks_cache_file}")
print("JWKS downloaded and cached successfully")
# Extract public key coordinates from JWKS
jwks_data = json.loads(jwks_json)
if not jwks_data.get('keys') or len(jwks_data['keys']) == 0:
raise Exception("No keys found in JWKS")
key = jwks_data['keys'][0]
x_coordinate = key['x']
y_coordinate = key['y']
# Validate the token
result = validate_jwt_token(sample_token, jwks_json)
if result['is_valid']:
claims = result['claims']
print("✅ Token validation successful!")
print(f"Campaign ID: {claims.get('cid')}")
print(f"Creative ID: {claims.get('crid')}")
print(f"RCLID: {claims.get('rclid')}")
print(f"Issued At: {datetime.fromtimestamp(claims.get('iat')).strftime('%Y-%m-%d %H:%M:%S UTC')}")
else:
print(f"❌ Token validation failed: {result['error']}")
if __name__ == "__main__":
main()
Input/Output Example
Input
- JWT Token: Copy the test token from the Overview page
- Public Key Source:
https://public-api.rokt.com/.well-known/jwks.json
Output
=== Python JWT Validator ===
Token: eyJhbGciOiJFUzI1NiIsImtpZCI6InJva3Qtc2lnbmluZy1rZXkiLCJ0eXAiOiJKV1QifQ...
JWKS URL: https://public-api.rokt.com/.well-known/jwks.json
Downloading JWKS from: https://public-api.rokt.com/.well-known/jwks.json
JWKS cached to: jwks_cache.json
JWKS downloaded and cached successfully
✅ Token validation successful!
Campaign ID: 3436085368692408324
Creative ID: 3437732754935906308
RCLID: 7db958dbd232247a4a8285a34d22fe0f4e9affa463bf5ee54e26721ab0df0e23
Issued At: 2025-08-20 15:10:01 UTC
How to Run
- Save the code to
rokt_jwt_validator.py
- Install dependencies:
pip install PyJWT cryptography
- Run:
python rokt_jwt_validator.py
Alternative Implementation with jose
For a more robust solution, you can also use the python-jose
library:
pip install python-jose[cryptography]
from jose import jwt
from jose.jwk import get_public_key
def validate_with_jose(token, jwks_json):
jwks = json.loads(jwks_json)
public_key = get_public_key(jwks['keys'][0])
claims = jwt.decode(
token,
public_key,
algorithms=['ES256']
)
return claims
Notes
-
The public key is retrieved from Rokt's JWKS endpoint
-
The example uses ECDSA-256 (ES256) algorithm for signature verification
-
Consider caching the public key for performance
-
The
cryptography
library provides better security than pure Python implementations