简单的 JWT 构造器和解析器

v1.0.0 2022-03-16 20:56 UTC

This package is auto-updated.

Last update: 2024-09-18 16:12:37 UTC


README

一个简单的库,用于使用 PHP (符合 RFC 7519) 编码和解码 JWT 令牌

依赖项

安装

composer require lostinvlg/jwt

创建 jwt

use Lostinvlg\Jwt\Algorithm;
use Lostinvlg\Jwt\Jwt;
use Lostinvlg\Jwt\Key;

$jwtId = '1dA8dDQ5lE';
$time = time();
$jwt = new Jwt();

$token = $jwt
    ->getBuilder()
    ->setKey(new Key('YOUR_SECRET_KEY_STRING', Algorithm::HS256))
    ->setIssuedBy('https://example.com')
    ->setAudience('https://example.com')
    ->setIssuedAt($time)
    ->setNotBefore($time + 10)
    ->setExpiresAt($time + 3600)
    ->setIdentifiedBy($jwtId)
    ->setClaim('user_id', 1)
    ->setClaim('role_id', 'admin')
    ->getToken();

$encoded = (string) $token; // contains jwt encoded string

$token->getClaim('user_id'); // equals 1
$token->getClaim('role_id'); // equals "admin"
$token->getClaim('exp'); // returns expires timestamp

从字符串解析

use Lostinvlg\Jwt\Algorithm;
use Lostinvlg\Jwt\Jwt;
use Lostinvlg\Jwt\Key;

$jwt = new Jwt();
$token = $jwt->getParser(new Key('YOUR_SECRET_KEY_STRING', Algorithm::HS256))->parse($encoded);

$token->getClaim('user_id'); // equals 1
$token->getClaim('role_id'); // equals "admin"
$token->getClaim('exp'); // returns expires timestamp

许可

MIT