Aller au contenu principal

Exemple de Validation JWT en Java

⚠️ 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 mettre en œuvre la gestion des clés JWKS différemment en fonction de votre infrastructure - comme en utilisant la gestion de la configuration, des 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 Java.

PrérequisLien direct vers Prérequis

Ajoutez les dépendances suivantes à votre pom.xml:

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>

Exemple CompletLien direct vers Exemple Complet

package com.rokt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.util.Base64;
import java.util.Date;

public class RoktJwtValidator {

// Copy the test token from the Overview page
private static final String SAMPLE_JWT_TOKEN = "PASTE_TEST_TOKEN_HERE";

// JWKS endpoint URL
private static final String JWKS_URL = "https://public-api.rokt.com/.well-known/jwks.json";

public static void main(String[] args) {
try {
System.out.println("=== Java JWT Validator ===");
System.out.println("Token: " + SAMPLE_JWT_TOKEN.substring(0, 50) + "...");
System.out.println("JWKS URL: " + JWKS_URL);
System.out.println();

// Download and cache JWKS
String jwksJson = downloadAndCacheJWKS(JWKS_URL, JWKS_CACHE_FILE);
System.out.println("JWKS downloaded and cached successfully");

// Extract public key coordinates from JWKS
String[] coordinates = extractKeyCoordinates(jwksJson);
String xCoordinate = coordinates[0];
String yCoordinate = coordinates[1];

// Create ECDSA public key from JWK coordinates
Key publicKey = createECDSAPublicKey(xCoordinate, yCoordinate);

// Validate JWT token
Claims claims = validateJWT(SAMPLE_JWT_TOKEN, publicKey);

System.out.println("✅ Token validation successful!");
System.out.println("Campaign ID: " + claims.get("cid"));
System.out.println("Creative ID: " + claims.get("crid"));
System.out.println("RCLID: " + claims.get("rclid"));
System.out.println("Issued At: " + new Date(claims.getIssuedAt().getTime()) + " UTC");"

} catch (Exception e) {
System.err.println("❌ Token validation failed: " + e.getMessage());
e.printStackTrace();
}
}

private static Claims validateJWT(String token, Key publicKey) {
return Jwts.parserBuilder()
.setSigningKey(publicKey)
.setAllowedClockSkewSeconds(60) // Allow 1 minute clock skew
.build()
.parseClaimsJws(token)
.getBody();
}

private static Key createECDSAPublicKey(String xCoordinate, String yCoordinate) throws Exception {
// Decode base64url encoded coordinates
byte[] xBytes = Base64.getUrlDecoder().decode(xCoordinate);
byte[] yBytes = Base64.getUrlDecoder().decode(yCoordinate);

// Convert to BigInteger
BigInteger x = new BigInteger(1, xBytes);
BigInteger y = new BigInteger(1, yBytes);

// Use standard P-256 curve from AlgorithmParameters
java.security.AlgorithmParameters parameters = java.security.AlgorithmParameters.getInstance("EC");
parameters.init(new java.security.spec.ECGenParameterSpec("secp256r1"));
ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);

// Create ECDSA public key spec
ECPublicKeySpec spec = new ECPublicKeySpec(
new ECPoint(x, y),
ecParameterSpec
);

// Generate public key
KeyFactory keyFactory = KeyFactory.getInstance("EC");
return keyFactory.generatePublic(spec);
}
}

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

=== Java JWT Validator ===
Token: eyJhbGciOiJFUzI1NiIsImtpZCI6InJva3Qtc2lnbmluZy1rZX...
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: Wed Aug 20 15:10:01 AEST 2025 UTC

Comment ExécuterLien direct vers Comment Exécuter

  1. Créez un projet Maven avec pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.rokt</groupId>
<artifactId>jwt-validator</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>

<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
  1. Enregistrez le code dans src/main/java/com/rokt/RoktJwtValidator.java
  2. Exécutez : mvn compile exec:java -Dexec.mainClass="com.rokt.RoktJwtValidator"

Utilisation directe des fichiers JARLien direct vers Utilisation directe des fichiers JAR

  1. Téléchargez les fichiers JAR de JJWT
  2. Enregistrez le code dans RoktJwtValidator.java
  3. Compilez : javac -cp ".:jjwt-api-0.11.5.jar:jjwt-impl-0.11.5.jar:jjwt-jackson-0.11.5.jar" RoktJwtValidator.java
  4. Exécutez : java -cp ".:jjwt-api-0.11.5.jar:jjwt-impl-0.11.5.jar:jjwt-jackson-0.11.5.jar" RoktJwtValidator

RemarquesLien direct vers Remarques

  • La clé publique est récupérée depuis le point d'accès 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

Cet article vous a-t-il été utile ?