okneloper/jwt-validators

lcobucci/jwt v3 的 JWT 验证库

v1.0.1 2018-11-18 00:15 UTC

This package is auto-updated.

Last update: 2024-09-19 10:09:33 UTC


README

轻松验证 lcobucci/jwt JWTs,当需要时添加自定义验证器。此包旨在与 lcobucci/jwt v3 一起使用。V4 将包括验证改进,因此可能不需要任何额外的包来设置令牌验证。

安装

composer require okneloper/jwt-validators

验证令牌

use Lcobucci\JWT\Builder;

$token = (new Builder())->setIssuer('http://example.com') // Configures the issuer (iss claim)
    ->setAudience('http://example.org') // Configures the audience (aud claim)
    ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
    ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
    ->setNotBefore(time() + 60) // Configures the time that the token can be used (nbf claim)
    ->setExpiration(time() + 3600) // Configures the expiration time of the token (nbf claim)
    ->set('uid', 1) // Configures a new claim, called "uid"
    ->getToken(); // Retrieves the generated token


$validator = new \Okneloper\JwtValidators\Validator();
// require the iss claim is present
$validator->add(new ClaimPresenceValidator('iss'));
// require that token lifetime is not longer than 120 seconds 
$validator->addValidator(new LifetimeValidator(60));

// validate the token
if (!$validator->validates($token)) {
    $errors = $validator->getErrors();
}

包含的验证器

ClaimPresenceValidator

验证特定声明是否存在。

$validator->add(new ClaimPresenceValidator('iss')); // require iss claim
$validator->add(new ClaimPresenceValidator('sub')); // require sub claim

ExpirationValidator

验证 exp 声明是否存在且令牌未过期。

$validator->add(new ExpirationValidator());

LifetimeValidator

验证令牌有效期是否小于或等于秒数。对于验证由其他发行者签发的令牌很有用。

$validator->addValidator(new LifetimeValidator(60)); // 60 seconds

SignaturePresenceValidator

验证令牌是否已签名。这将在尝试验证未签名的令牌的签名时防止抛出异常。

$validator->addValidator(new SignaturePresenceValidator());

UniqueJtiValidator

验证令牌不在自定义存储中。要使用它,您需要传递一个实现 TokenExistenceChecker 接口的实例。这是一个简单的接口,允许您定义如何检查令牌是否存在于您的记录中。示例用法

// find the user by uid stored in the token
$user = User::find($token->getClaim('uid'));
// example checker that will check the database if a token id
// previously provided by the $user has been processed before
$checker = new CustomChecker($user);
// add this validator same as any other
$validator->addValidator(new UniqueJtiValidator($checker));

编写自定义验证器

编写自定义验证器有两种方法,具体取决于您需要的验证器的复杂度。

ITokenValidator 接口

一个实现 ITokenValidator 接口的类。此接口有两个方法

interface ITokenValidator
{
    /**
     * Returns true if the token validates against this validator
     * @param \Lcobucci\JWT\Token $token
     * @return bool
     */
    public function validates(\Lcobucci\JWT\Token $token, $breakOnFirstError = true);

    /**
     * @return string
     */
    public function getErrors();
}

简单地实现此接口,并将其添加到您的验证器列表中。

TokenValidator 类

为了简化编写验证器的过程,库包含一个实现此接口和装饰器模式的抽象类,这允许您链接多个验证器。例如,您想在验证值之前检查声明是否存在。将此逻辑拆分为两个单独的验证器允许提供干净且精确的错误消息。这对使用您的 API 的开发人员非常有帮助。

您只需要定义您的错误消息和验证方法即可

class CustomValidator extends TokenValidator
{
    public function __construct()
    {
        // the second argument is optional
        parent::__construct("The username is too long", new ClaimPresenceValidator('username'));
    }

    protected function isValid(\Lcobucci\JWT\Token $token)
    {
        return strlen($token->getClaim('username')) <= 10;
    }
}