JWT::decode PHP Method

decode() public static method

Decodes a JWT string into a PHP object.
public static decode ( string $jwt, string | Array | null $key = null, boolean $verify = true ) : object
$jwt string The JWT
$key string | Array | null The secret key, or map of keys
$verify boolean Don't skip verification process
return object The JWT's payload as a PHP object
    public static function decode($jwt, $key = null, $verify = true)
    {
        $tks = explode('.', $jwt);
        if (count($tks) != 3) {
            throw new UnexpectedValueException('Wrong number of segments');
        }
        list($headb64, $bodyb64, $cryptob64) = $tks;
        if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) {
            throw new UnexpectedValueException('Invalid header encoding');
        }
        if (null === ($payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64)))) {
            throw new UnexpectedValueException('Invalid claims encoding');
        }
        $sig = JWT::urlsafeB64Decode($cryptob64);
        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 (!JWT::verify("{$headb64}.{$bodyb64}", $sig, $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 $payload;
    }

Usage Example

Example #1
1
 /**
  * Inicialización de la petición
  * ****************************************
  * Aqui debe ir la autenticación de la API
  * ****************************************
  */
 protected final function initialize()
 {
     $router = Router::get();
     // Habilitando CORS para hacer funcional el RESTful
     header('Access-Control-Allow-Origin: *');
     header('Access-Control-Allow-Credentials: true');
     // Habilitar todos los headers que recibe (Authorization sobre todo para manejar JWT)
     $requestHeaders = $this->getHeaders();
     $request = array_keys($requestHeaders);
     header("Access-Control-Allow-Headers: " . implode(',', $request) . ',Authorization');
     // Verificar los accesos y validez de token
     // TODO: Implementar un limit a la consultas de getAll() por seguridad cuando la vista sea pública
     if (!($this->publicView && ($router['method'] == 'GET' || $router['method'] == 'OPTIONS'))) {
         // Precendia del Token
         if (!empty($requestHeaders['Authorization'])) {
             $token = $requestHeaders['Authorization'];
             $this->me = JWT::decode(str_replace('Bearer ', '', $token), TOKEN);
             $now = time();
             // Verificamos que este activo
             if ($now >= $this->me->exp) {
                 $this->setCode(403);
                 die('Error 403 - Acceso Denegado');
             }
         } else {
             $this->setCode(403);
             die('Error 403 - Acceso Denegado');
         }
     }
 }
All Usage Examples Of JWT::decode