Exemple #1
0
 public function verifyToken($key, $token = null)
 {
     if (empty($token)) {
         $token = $this;
     }
     if ($token instanceof JWT) {
         $token = $token->getToken();
     }
     if (empty($key)) {
         throw new InvalidArgumentException('Key may not be empty');
     }
     $token = explode('.', $token);
     if (count($token) != 3) {
         throw new UnexpectedValueException('Wrong number of segments');
     }
     list($headB64, $payloadB64, $cryptoB64) = $token;
     if (null === ($header = JWT::jsonDecode(JWT::URLSafeB64Decode($headB64)))) {
         throw new UnexpectedValueException('Invalid header encoding');
     }
     if (null === ($payload = JWT::jsonDecode(JWT::URLSafeB64Decode($payloadB64)))) {
         throw new UnexpectedValueException('Invalid claims encoding');
     }
     $sign = JWT::URLSafeB64Decode($cryptoB64);
     if (empty($header->alg) || $header->alg === 'none') {
         throw new DomainException('Empty algorithm');
     }
     if (empty(self::$supportedAlg[$header->alg])) {
         throw new DomainException('Algorithm not supported');
     }
     if (is_array($key) || $key instanceof \ArrayAccess) {
         if (isset($header->kid)) {
             $key = $key[$header->kid];
         } else {
             throw new DomainException('"kid" empty, unable to lookup correct key');
         }
     }
     if (!JWT::verify("{$headB64}.{$payloadB64}", $sign, $key, $header->alg)) {
         return false;
     }
     if (isset($payload->nbf) && $payload->nbf > time() + self::$exp) {
         throw new BeforeValidException('Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf));
     }
     if (isset($payload->iat) && $payload->iat > time() + self::$exp) {
         throw new BeforeValidException('Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat));
     }
     if (isset($payload->exp) && time() - self::$exp >= $payload->exp) {
         throw new ExpiredException('Expired token');
     }
     return true;
 }