emarref/jwt

JWT 实现

维护者

详细信息

github.com/emarref/jwt

源代码

问题

1.0.3 2016-09-05 20:33 UTC

README

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

Build Status Scrutinizer Code Quality

功能包括

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

⚠️ 本库的 v1.0.2 及以下版本在使用对称加密时容易受到时间攻击。有关更多信息,请参阅 #20。请尽快更新到 >= v1.0.3 以解决此漏洞。

此库不会受到常见的 加密漏洞 的影响。

安装

composer require emarref/jwt

使用

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

use Emarref\Jwt\Claim;

$token = new Emarref\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 Emarref\Jwt\Jwt();

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

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

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

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

在 wiki 中可以找到使用 Rs256 加密与密钥对示例 - 使用 RS256 加密

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

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

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

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

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

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

测试

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

./bin/phpunit ./test

进一步阅读