/** * @author Brent Shaffer * @license MIT License */ /** * Sépare les composantes du jeton, détecte les erreurs de format, vérifie la signature et retourne la charge utile ou false en cas d'erreur. * * @param mixed $jwt : le jeton JWT * @param mixed $key : la clé publique * @param mixed $allowedAlgorithms : un array des codes d'algorithmes autorisés (sous ensemble de HS256, HS384 ou HS512, RS256, RS384 et RS512). Si ce paramètre est précisé, le jeton doit indiquer l'algorithme et celui-ci doit être compris dans l'array. * @param mixed return : charge utile (tableau associatif) ou false. */ function decode($jwt, $key = null, $allowedAlgorithms = true) { if (!strpos($jwt, '.')) { return false; } $tks = explode('.', $jwt); if (count($tks) != 3) { return false; } list($headb64, $payloadb64, $cryptob64) = $tks; if (null === ($header = json_decode($this->urlSafeB64Decode($headb64), true))) { return false; } if (null === $payload = json_decode($this->urlSafeB64Decode($payloadb64), true)) { return false; } $sig = $this->urlSafeB64Decode($cryptob64); if ((bool) $allowedAlgorithms) { if (!isset($header['alg'])) { return false; } // check if bool arg supplied here to maintain BC if (is_array($allowedAlgorithms) && !in_array($header['alg'], $allowedAlgorithms)) { return false; } if (!$this->verifySignature($sig, "$headb64.$payloadb64", $key, $header['alg'])) { return false; } } return $payload; } function verifySignature($signature, $input, $key, $algo = 'HS256') { // use constants when possible, for HipHop support switch ($algo) { case'HS256': case'HS384': case'HS512': return $this->hash_equals( $this->sign($input, $key, $algo), $signature ); case 'RS256': return openssl_verify($input, $signature, $key, defined('OPENSSL_ALGO_SHA256') ? OPENSSL_ALGO_SHA256 : 'sha256') === 1; case 'RS384': return @openssl_verify($input, $signature, $key, defined('OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 : 'sha384') === 1; case 'RS512': return @openssl_verify($input, $signature, $key, defined('OPENSSL_ALGO_SHA512') ? OPENSSL_ALGO_SHA512 : 'sha512') === 1; default: throw new \InvalidArgumentException("Unsupported or invalid signing algorithm."); } }