Exemple de Validation JWT en Python
⚠️ Avis Important : Ceci est un exemple de base à des fins de démonstration uniquement. Pour une utilisation en production, veuillez rechercher et mettre en œuvre les meilleures pratiques spécifiques à votre pile logicielle, vos exigences de sécurité et votre environnement de déploiement. Suivez toujours les directives de sécurité de votre organisation et envisagez d'utiliser des bibliothèques et des frameworks JWT établis.
📝 Remarque : Cet exemple démontre le téléchargement de JWKS et la mise en cache de fichiers à des fins éducatives. Dans les environnements de production, vous pouvez choisir de gérer les clés JWKS différemment en fonction de votre infrastructure - comme en utilisant la gestion de configuration, les variables d'environnement ou votre stratégie de mise en cache préférée.
Cet exemple montre comment valider les jetons JWT de Rokt en utilisant Python.
PrérequisLien direct vers Prérequis
Installez les paquets requis :
pip install PyJWT cryptography
Exemple CompletLien direct vers Exemple Complet
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'],
leeway=60 # Allow 1 minute clock skew
)
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 24 hours 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=24):
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()
Exemple d'Entrée/SortieLien direct vers Exemple d'Entrée/Sortie
EntréeLien direct vers Entrée
- Jeton JWT : Copiez le jeton de test depuis la page d'aperçu
- Source de la Clé Publique :
https://public-api.rokt.com/.well-known/jwks.json
SortieLien direct vers Sortie
=== 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
Comment ExécuterLien direct vers Comment Exécuter
- Enregistrez le code dans
rokt_jwt_validator.py - Installez les dépendances :
pip install PyJWT cryptography - Exécutez :
python rokt_jwt_validator.py
Implémentation Alternative avec joseLien direct vers Implémentation Alternative avec jose
Pour une solution plus robuste, vous pouvez également utiliser la bibliothèque python-jose :
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
RemarquesLien direct vers Remarques
-
La clé publique est récupérée depuis le point de terminaison JWKS de Rokt
-
L'exemple utilise l'algorithme ECDSA-256 (ES256) pour la vérification de la signature
-
Envisagez de mettre en cache la clé publique pour améliorer les performances
-
La bibliothèque
cryptographyoffre une meilleure sécurité que les implémentations en pur Python