该包已被废弃,不再维护。作者建议使用 firebase/php-jwt 包。

JSON对象签名和加密库,用于PHP。

v1.0.0 2015-12-09 17:51 UTC

This package is auto-updated.

Last update: 2020-10-28 14:19:49 UTC


README

Build Status Scrutinizer Code Quality Code Coverage SensioLabs Insight StyleCI Latest Stable Version License

提供JWS(JSON Web Signature)规范的轻量级实现。这个库是 namshi/jose 的分支。

要求

  1. PHP 5.4.8+(在5.4,5.5,5.6,7和HHVM上测试过)
  2. (可选) OpenSSL 扩展(当使用RSA/ECDSA签名者时)
  3. (可选) symfony/polyfill-php56 库(当PHP版本小于5.6时使用HMAC签名者)

安装

composer require zenstruck/jwt

当在PHP版本小于5.6时使用HMAC签名者

composer require symfony/polyfill-php56

基本用法

  1. 创建、编码并发送令牌给用户

    use Zenstruck\JWT\Token;
    use Zenstruck\JWT\Signer\HMAC\HS256;
    
    // create the token
    $token = new Token([
        'username' => 'kevin', // custom claim
        'iss' => 'zenstruck', // set issuer
        'exp' => time() + 86400, // set expiry claim to 1 day from now
    ]);
    
    // can access claims
    $token->get('username'); // kevin
    $token->get('non-existant'); // null
    
    // sign the token
    $token->sign(new HS256(), 'my secret key');
    
    $encodedTokenForUser = (string) $token;
    
    // ...pass to user
  2. 从用户处获取编码的令牌,解码、验证、验证并访问自定义声明

    use Zenstruck\JWT\Token;
    use Zenstruck\JWT\Signer\HMAC\HS256;
    use Zenstuck\JWT\Validator\ExpiresAtValidator;
    use Zenstuck\JWT\Validator\IssuerValidator;
    use Zenstruck\JWT\Exception\MalformedToken;
    use Zenstruck\JWT\Exception\UnverifiedToken;
    use Zenstruck\JWT\Exception\Validation\ExpiredToken;
    use Zenstruck\JWT\Exception\ValidationFailed;
    
    $encodedTokenFromUser = // ...fetched from user
    
    try {
        $decodedToken = Token::fromString($encodedTokenFromUser);
    } catch (MalformedToken $e) {
        // token is not correctly formed
    }
    
    // at this point $decodedToken is a JWT but is not yet verified or validated
    
    try {
        $decodedToken->verify(new HS256(), 'my secret key');
    } catch (UnverifiedToken $e) {
        // token could not be verified
    }
    
    try {
        $decodedToken->validate(new ExpiresAtValidator());
        $decodedToken->validate(new IssuerValidator('zenstruck'));
    } catch (ExpiredToken $e) {
        // the token has expired
    } catch (ValidationFailed $e) {
        // token is invalid - in this case, the issuer does not match
    }
    
    // can access claims
    $token->get('username'); // kevin
    $token->get('non-existant'); // null

令牌构建器

use Zenstruck\JWT\TokenBuilder;

$token = (new TokenBuilder())
    ->issuer('kevin')
    ->subject('zenstruck\jwt')
    ->audience('php community')
    ->expiresAt(new \DateTime('+1 day'))
    ->notBefore(new \DateTime('+1 hour'))
    ->issuedAt() // can pass \DateTime object - uses current time by default
    ->id('foo')
    ->set('foo', 'bar') // set custom claims
    ->create(); // instance of Zenstruck\JWT\Token

签名者

HMAC

这些签名者需要使用相同的密钥字符串进行签名和验证。

算法 签名者类
HS256 Zenstruck\JWT\Signer\HMAC\HS256
HS384 Zenstruck\JWT\Signer\HMAC\HS384
HS512 Zenstruck\JWT\Signer\HMAC\HS512

用法

$token = // ... instance of Zenstruck\JWT\Token
$signer = // an instance of one of the classes in the table above

$token->sign($signer, 'my secret key');
$token->verify($signer, 'my secret key'); // verified
$token->verify($signer, 'invalid secret key'); // unverified - exception thrown

RSA/ECDSA (OpenSSL)

这些签名者需要签名时使用私钥,验证时使用公钥。

  • 私钥:一个字符串(密钥内容或文件名)、资源或 Zenstruck\JWT\Signer\OpenSSL\PrivateKey 的实例
  • 公钥:一个字符串(密钥内容或文件名)、资源或 Zenstruck\JWT\Signer\OpenSSL\PublicKey 的实例
  • 密钥链:包含公钥和私钥的 Zenstruck\JWT\Signer\OpenSSL\Keychain 的实例。可以作为密钥传递给 Signer::sign()Signer::verify()
算法 签名者类
RS256 Zenstruck\JWT\Signer\OpenSSL\RSA\RS256
RS384 Zenstruck\JWT\Signer\OpenSSL\RSA\RS384
RS512 Zenstruck\JWT\Signer\OpenSSL\RSA\RS512
ES256 Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES256
ES384 Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES384
ES512 Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES512

用法

$token = // ... instance of Zenstruck\JWT\Token
$signer = // an instance of one of the classes in the table above
$privateKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PrivateKey, instance of Zenstruck\JWT\Signer\OpenSSL\Keychain
$publicKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PublicKey, instance of Zenstruck\JWT\Signer\OpenSSL\Keychain

$token->sign($signer, $privateKey);
$token->verify($signer, $publicKey); // verified
$token->verify($signer, '/path/to/unmatched/public/key'); // unverified - exception thrown
密钥链

密钥链包含公钥和私钥。当传递密钥链作为密钥时,签名者使用正确的密钥进行操作。

use Zenstruck\JWT\Signer\OpenSSL\Keychain;

$token = // ... instance of Zenstruck\JWT\Token
$signer = // an instance of one of the classes in the table above
$privateKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PrivateKey
$publicKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PublicKey

$keychain = new Keychain($publicKey, $privateKey, 'my passphrase');

$token->sign($signer, $keychain);
$token->verify($signer, $keychain); // verified

验证

验证器 描述
Zenstruck\JWT\Validator\IssuerValidator 确保存在且匹配预期的iss声明
Zenstruck\JWT\Validator\SubjectValidator 确保存在且匹配预期的sub声明
Zenstruck\JWT\Validator\AudienceValidator 确保存在且匹配预期的aud声明
Zenstruck\JWT\Validator\ExpiresAtValidator 确保存在的exp声明不大于预期时间
Zenstruck\JWT\Validator\NotBeforeValidator 确保存在的nbf声明不小于预期时间
Zenstruck\JWT\Validator\IssuedAtValidator 确保存在且匹配预期的iat声明
Zenstruck\JWT\Validator\IdAtValidator 确保存在且匹配预期的jti声明
Zenstruck\JWT\Validator\ChainValidator 将上述任何验证器组合在一起

使用方法

use Zenstruck\JWT\Validator\IssuerValidator;
use Zenstruck\JWT\Validator\AudienceValidator;
use Zenstruck\JWT\Validator\ChainValidator;

$token = // ... instance of Zenstruck\JWT\Token
$validator = new ChainValidator([new IssuerValidator(), new AudienceValidator()]);

try {
    $token->validate($validator);
} catch (ValidationFailed $e) {
    $reason = $e->getMessage();
}

ValidatorBuilder

$validator = (new ValidatorBuilder())
    ->issuer('kevin')
    ->subject('zenstruck\jwt')
    ->audience('php community')
    ->expiresAt()
    ->notBefore()
    ->issuedAt(time())
    ->id('foo')
    ->create(); // instance of Zenstruck\JWT\Validator\ChainValidator