メインコンテンツまでスキップ

Python JWT Validation Example

⚠️ 重要なお知らせ: これはデモンストレーション目的の基本的な例です。実運用で使用する場合は、ソフトウェアスタック、セキュリティ要件、デプロイメント環境に特化したベストプラクティスを調査し実装してください。常に組織のセキュリティガイドラインに従い、確立されたJWTライブラリやフレームワークの使用を検討してください。

📝 注記: この例は教育目的でJWKSのダウンロードとファイルキャッシングを示しています。実運用環境では、インフラストラクチャに基づいて、構成管理、環境変数、または好みのキャッシング戦略を使用してJWKSキー管理を実装することを選択できます。

この例は、Pythonを使用してRokt JWTトークンを検証する方法を示しています。

前提条件前提条件 への直接リンク

必要なパッケージをインストールします:

pip install PyJWT cryptography

完全な例完全な例 への直接リンク

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()

入出力例入出力例 への直接リンク

入力入力 への直接リンク

  • JWTトークン: 概要ページからテストトークンをコピーします
  • 公開鍵ソース: https://public-api.rokt.com/.well-known/jwks.json

出力出力 への直接リンク

=== 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

実行方法実行方法 への直接リンク

  1. コードをrokt_jwt_validator.pyに保存します
  2. 依存関係をインストールします: pip install PyJWT cryptography
  3. 実行します: python rokt_jwt_validator.py

joseを使用した代替実装joseを使用した代替実装 への直接リンク

より堅牢なソリューションとして、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

注記注記 への直接リンク

  • 公開鍵はRoktのJWKSエンドポイントから取得されます

  • 例では署名検証にECDSA-256 (ES256)アルゴリズムを使用しています

  • パフォーマンス向上のために公開鍵をキャッシュすることを検討してください

  • cryptographyライブラリは純粋なPython実装よりも優れたセキュリティを提供します

この記事は役に立ちましたか?