emarref / jwt
JWT 实现
1.0.3
2016-09-05 20:33 UTC
This package is auto-updated.
Last update: 2024-08-23 13:35:12 UTC
README
PHP 中 JSON Web Token (JWT) 草案的实现。有关 JWT 的更多信息,请参阅 jwt.io。
功能包括
- 令牌序列化
- 令牌反序列化
- 令牌验证
- 验证
aud、exp、iss、nbf、sub声明
- 验证
- 对称加密
- 支持
NONE、HS256、HS384、HS512算法
- 支持
- 非对称加密
- 支持
RS256、RS384、RS512算法 - 计划支持
ES256、ES384、ES512、PS256、PS384、PS512算法
- 支持
⚠️ 本库的 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