/** * Decodes a JWT string into a PHP object. * * @param string $jwt The JWT * @param string|Array|null $key The secret key, or map of keys * @param bool $verify Don't skip verification process * * @return object The JWT's payload as a PHP object * * @throws DomainException Algorithm was not provided * @throws UnexpectedValueException Provided JWT was invalid * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat' * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim * * @uses jsonDecode * @uses urlsafeB64Decode */ public static function decode($jwt, $key = null, $verify = true) { $tks = JWT::split($jwt); if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($tks['header'])))) { throw new UnexpectedValueException('Invalid header encoding'); } if (null === ($payload = JWT::jsonDecode(JWT::urlsafeB64Decode($tks['body'])))) { throw new UnexpectedValueException('Invalid claims encoding'); } $signature = JWT::urlsafeB64Decode($tks['sig']); if ($verify) { if (empty($header->alg)) { throw new DomainException('Empty algorithm'); } if (is_array($key)) { if (isset($header->kid)) { $key = $key[$header->kid]; } else { throw new DomainException('"kid" empty, unable to lookup correct key'); } } // Check the signature if ($key && !JWT::verify($tks['header'], $tks['body'], $signature, $key, $header->alg)) { throw new SignatureInvalidException('Signature verification failed'); } // Check if the nbf if it is defined. This is the time that the // token can actually be used. If it's not yet that time, abort. if (isset($payload->nbf) && $payload->nbf > time()) { throw new BeforeValidException('Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)); } // Check that this token has been created before 'now'. This prevents // using tokens that have been created for later use (and haven't // correctly used the nbf claim). if (isset($payload->iat) && $payload->iat > time()) { throw new BeforeValidException('Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)); } // Check if this token has expired. if (isset($payload->exp) && time() >= $payload->exp) { throw new ExpiredException('Expired token'); } } return array($header, $payload, $signature); }
public function testVerify() { $msg = 'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.Iio6aHR0cDovL2FwcGxpY2F0aW9uL2NsaWNreT9ibGFoPTEuMjMmZi5vbz00NTYgQUMwMDAgMTIzIg.E_U8X2YpMT5K1cEiT_3-IvBYfrdIFIeVYeOqre_Z5Cg'; $tks = JWT::split($msg); list(, , $signature) = JWT::decode($tks); $this->assertTrue(JWT::verify($tks['header'], $tks['body'], $signature, 'my_key')); }