55 lines
2.0 KiB
PHP
55 lines
2.0 KiB
PHP
<?php
|
|
// utils/JWT.php
|
|
|
|
class JWT {
|
|
// Encode en Base64 utilisable dans une URL
|
|
private static function base64UrlEncode($text) {
|
|
return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($text));
|
|
}
|
|
|
|
// Décode le Base64 d'URL
|
|
private static function base64UrlDecode($text) {
|
|
$base64 = str_replace(['-', '_'], ['+', '/'], $text);
|
|
return base64_decode($base64 . substr('===', (strlen($base64) % 4) ?: 4));
|
|
}
|
|
|
|
// 1. GÉNÉRER LE TOKEN
|
|
public static function generate($payload, $secret) {
|
|
$header = json_encode(['alg' => 'HS256', 'typ' => 'JWT']);
|
|
|
|
// On ajoute une date d'expiration (ex: valide 30 jours)
|
|
$payload['exp'] = time() + (30 * 24 * 60 * 60);
|
|
$payload_json = json_encode($payload);
|
|
|
|
$base64UrlHeader = self::base64UrlEncode($header);
|
|
$base64UrlPayload = self::base64UrlEncode($payload_json);
|
|
|
|
// Signature HMAC SHA256
|
|
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secret, true);
|
|
$base64UrlSignature = self::base64UrlEncode($signature);
|
|
|
|
return $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
|
|
}
|
|
|
|
// 2. VÉRIFIER LE TOKEN
|
|
public static function validate($token, $secret) {
|
|
$part = explode('.', $token);
|
|
if (count($part) !== 3) return false;
|
|
|
|
list($header, $payload, $signature) = $part;
|
|
|
|
// On refait la signature pour vérifier si elle correspond
|
|
$valid_signature = hash_hmac('sha256', $header . "." . $payload, $secret, true);
|
|
$valid_base64UrlSignature = self::base64UrlEncode($valid_signature);
|
|
|
|
if ($signature !== $valid_base64UrlSignature) return false;
|
|
|
|
$payload_data = json_encode(json_decode(self::base64UrlDecode($payload), true));
|
|
$data = json_decode($payload_data, true);
|
|
|
|
// Vérification de la date d'expiration
|
|
if (isset($data['exp']) && $data['exp'] < time()) return false;
|
|
|
|
return $data; // Renvoie les données (user_id) si tout est OK
|
|
}
|
|
} |