用于编码/解码 JWT (Json Web Tokens) 的库

v1.0.0 2020-03-06 11:46 UTC

This package is auto-updated.

Last update: 2024-09-07 21:28:58 UTC


README

安装

composer require papalapa/jwt

PEM 密钥生成命令

openssl req -x509 -nodes -newkey rsa:2048 -keyout jwt-key.pem -out jwt-cert.pem -days 365

使用密钥字符串的示例

use papalapa\jwt\Encoder;
use papalapa\jwt\Decoder;
use papalapa\jwt\KeyStorage;
use papalapa\jwt\PayloadOptions;use papalapa\jwt\Signers\HS256;

$secretString = '00000000000000000000000000000000';
$keyStorage = new KeyStorage($secretString);

$myAudience = 'my-site';
$encoder = new Encoder($myAudience, $keyStorage);
$token = $encoder->encode(new HS256(), ['username' => 'John Doe']); // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IkpvaG4gRG9lIn0.lv1XJ5-AKeciLPbEr0vV5XMgfdZMrUnK2t0GKkZapjU

$decoder = new Decoder('my-site', $keyStorage);
$payload = $decoder->decode($token); // ['username' => 'John Doe']

// with key pair
$cert = '/home/user/cert/cert.pem';
$key = '/home/user/cert/key.pem';
$keyStorage = new KeyStorage($secretString, $cert, $key);

// activation-time check (nbf attribute)
$decoder->setActivationCheck(true); // true by default
$payload = ['username' => 'John Doe', 'nbf' => '2030-01-01T00:00:00'];

// expiration-time check (exp attribute)
$decoder->setExpirationCheck(true); // true by default
$payload = ['username' => 'John Doe', 'exp' => '2030-01-01T00:00:00'];

// audience check (aud attribute)
$decoder->setAudienceCheck(true); // true by default
$payload = ['username' => 'John Doe', 'aud' => ['my-site', 'his-site', 'our-site']];

// using another config with attribute names in payload
$payloadOptions = new PayloadOptions([
    'aud' => 'audienceName',
    'exp' => 'expiredAt',
    'iss' => 'issuer'
]);
// using setters
$payloadOptions->setNbfArgument('activatedAt');
$payloadOptions->setAlgArgument('hasher');
$decoder = new Decoder($myAudience, $keyStorage, $payloadOptions);

测试

使用 phpunit 运行测试: composer test

测试覆盖率

使用 phpunit 运行 html-coverage 测试: composer coverage

帮助

JWT 在线测试: https://jwt.net.cn/