iachilles / pjwt
PHP 实现的 JSON Web Token (JWT)。它提供了一种简单的方法来创建、签名和验证 JWT。
1.0.0
2014-11-23 22:00 UTC
Requires
- php: >=5.4.0
This package is auto-updated.
Last update: 2024-09-22 05:22:46 UTC
README
pJWT
PHP 实现的JSON Web Token (JWT)。它提供了一种简单的方法来创建、签名和验证 JWT。
以下特性被支持
- JWT 断言(iat, nbf, exp, jti)的内置验证。
- 对称和非对称算法用于保护完整性
要求
PHP 5.4.0 或更高版本。
安装
使用composer 安装 pJWT
composer require iachilles/pjwt
代码示例
- 创建 JWT
- 使用对称算法 HS256
$claims = ['iat' => time(), 'nbf' => time(), 'exp' => strtotime('+1 day'), 'iss' => 'domain.com', 'uid' => 1]; $headers = ['alg' => 'HS256', 'typ' => 'JWT']; $jws = new Jws($headers, $claims); $jws->privateKey = 'YoUr_SeCrEt'; $jws->sign(); //Returns URL-safe string representation of the digitally signed JWT. This encoded JWT can be sent to a user.
- 使用非对称算法 RS256
$claims = ['iat' => time(), 'nbf' => time(), 'exp' => strtotime('+1 day'), 'iss' => 'domain.com', 'uid' => 1]; $headers = ['alg' => 'RS256', 'typ' => 'JWT']; $jws = new Jws($headers, $claims); $jws->privateKey = 'file:///path/to/private/key.pem'; //Path to the PEM encoded private key. $jws->sign(); //Returns URL-safe string representation of the digitally signed JWT. This encoded JWT can be sent to a user.
如果私钥被密码加密,可以使用以下格式
$jws->privateKey = ['file:///path/to/private/key.pem', 'pAsSwOrd'];
- 防止重放攻击。为了防止重放攻击,您可以在创建 JWT 时将 'jti' 断言设置为 TRUE。
$claims = ['jti' => true, 'iat' => time(), 'nbf' => time(), 'exp' => strtotime('+1 day')]; $headers = ['alg' => 'RS256', 'typ' => 'JWT']; $jws = new Jws($headers, $claims);
-
解码和验证 JWT
$encodedJwt = 'abcdef.ghijklm.nopqrstuvw'; $jws = Jws::parse($encodedJwt); $jws->getPayload()->issuedAt; // 访问注册的 JWT 断言 $jws->getPayload()->getCustomClaim('user_id'); // 访问自定义断言。 $jws->getHeader()->getAlgorithm(); // 访问 JOSE 标头参数。
Verifying signature
```php
$encodedJwt = 'abcdef.ghijklm.nopqrstuvw';
$jws = Jws::parse($encodedJwt);
//For symmetric algorithm:
$jws->privateKey = 'YoUr_SeCrEt';
//For asymmetric algorithm:
$jws->certificate = 'file:///path/to/certificate.pem'; //Path to the PEM encoded X.509 certificate.
$jws->verify(); //TRUE if the signature is valid.
如果签名有效,您必须验证 JWT 断言。
$jws->getPayload()->verify(); //Returns TRUE if the JWT is valid, otherwise it returns a string that contains an error message.
要验证 "jti" 值,您需要创建两个匿名函数,并将它们作为参数传递给验证方法。
$setJti = function($jti) { //Writes "jti" value into storage. (E.g. Redis Db) }; //This function must return TRUE if the given value exists in storage, false otherwise. $getJti = function($jti) { //... }; $jws->getPayload()->verify($setJti, $getJti);