JWT 实现

v1.0.2 2024-05-28 15:02 UTC

This package is auto-updated.

Last update: 2024-09-28 16:00:03 UTC


README

这个PHP库是从 emarref/jwt 分支出来的,它需要与PHP8一起使用。

PHP中实现 JSON Web Token (JWT) 草案的库。有关JWT的更多信息,请参阅 jwt.io

特性包括

  • 令牌序列化
  • 令牌反序列化
  • 令牌验证
    • 验证 audexpissnbfsub 声明
  • 对称加密
    • 支持 NONEHS256HS384HS512 算法
  • 非对称加密
    • 支持 RS256RS384RS512 算法
    • 计划支持 ES256ES384ES512PS256PS384PS512 算法

这个库不受常见 加密漏洞 的影响。

安装

composer require rramacciani/jwt

使用方法

创建 Rramacciani\Jwt\Token 类的实例,然后进行配置。

use Rramacciani\Jwt\Claim;

$token = new Rramacciani\Jwt\Token();

// Standard claims are supported
$token->addClaim(new Claim\Audience(['audience_1', 'audience_2']));
$token->addClaim(new Claim\Expiration(new \DateTime('30 minutes')));
$token->addClaim(new Claim\IssuedAt(new \DateTime('now')));
$token->addClaim(new Claim\Issuer('your_issuer'));
$token->addClaim(new Claim\JwtId('your_id'));
$token->addClaim(new Claim\NotBefore(new \DateTime('now')));
$token->addClaim(new Claim\Subject('your_subject'));

// Custom claims are supported
$token->addClaim(new Claim\PublicClaim('claim_name', 'claim_value'));
$token->addClaim(new Claim\PrivateClaim('claim_name', 'claim_value'));

要使用令牌,创建JWT实例。

$jwt = new Rramacciani\Jwt\Jwt();

要获取用于传输的编码令牌,请调用 serialize() 方法。

$algorithm = new Rramacciani\Jwt\Algorithm\None();
$encryption = Rramacciani\Jwt\Encryption\Factory::create($algorithm);
$serializedToken = $jwt->serialize($token, $encryption);

现在 $serializedToken 变量包含您令牌的非加密base64编码字符串表示。要加密令牌,请将 Rramacciani\Jwt\Encryption\EncryptionInterface 的实例作为第二个参数传递给 serialize() 方法。

$algorithm = new Rramacciani\Jwt\Algorithm\Hs256('verysecret');
$encryption = Rramacciani\Jwt\Encryption\Factory::create($algorithm);
$serializedToken = $jwt->serialize($token, $encryption);

有关使用RS256加密与密钥对示例的说明,请参阅wiki - 使用RS256加密

要使用序列化令牌,首先使用JWT实例将其反序列化为 Rramacciani\Jwt\Token 对象。

$token = $jwt->deserialize($serializedToken);

要验证令牌的声明,首先设置用于验证令牌的上下文。加密是唯一的验证。

$context = new Rramacciani\Jwt\Verification\Context($encryption);
$context->setAudience('audience_1');
$context->setIssuer('your_issuer');

然后在对JWT实例使用 verify() 方法。

try {
    $jwt->verify($token, $context);
} catch (Rramacciani\Jwt\Exception\VerificationException $e) {
    echo $e->getMessage();
}

测试

这个库使用PHPUnit进行单元测试。请确保您已运行 composer install,然后调用

./bin/phpunit ./test

进一步阅读