PHP code example of wiseadmin / wise-jwt

1. Go to this page and download the library: Download wiseadmin/wise-jwt library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wiseadmin / wise-jwt example snippets


return [
    // 签名算法
    'algorithm' => 'HS256',

    // HMAC 密钥(HS256/384/512)
    'secret' => env('JWT_SECRET', 'your-secret-key-change-me'),

    // RSA 私钥/公钥路径(RS256/384/512)
    'private_key' => '',
    'public_key'  => '',

    // 签发者标识
    'issuer' => 'wise-jwt',

    // Token 有效期(秒),默认 2 小时
    'ttl' => 7200,

    // 续签窗口(秒),剩余有效期 < 此值时自动续签
    'refresh_ttl' => 1800,

    // 受众(可选)
    'audience' => null,

    // 时间容差(秒),用于处理时钟偏差
    'leeway' => 0,

    // 声明校验开关
    'validation' => [
        'check_expiration'  => true,    // 检查过期
        'check_not_before'  => true,    // 检查生效时间
        'check_issuer'      => true,    // 检查签发者
        'check_audience'    => false,   // 检查受众
    ],

    // 黑名单配置
    'blacklist' => [
        'enable' => true,
        'driver' => 'cache',            // cache / redis
        'prefix' => 'jwt:blacklist:',
    ],
];

use wise\jwt\facade\Jwt;

// 基本签发
$token = Jwt::issue($userId);
// → eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.xxx.yyy

// 附带自定义声明
$token = Jwt::issue($userId, [
    'role'   => 'admin',
    'dept_id' => 5,
]);

// 指定有效期(覆盖默认 ttl)
$token = Jwt::issue($userId, ['role' => 'admin'], 3600);  // 1小时

$token = app('jwt')->builder()
    ->subject($userId)
    ->claim('role', 'admin')
    ->claim('dept_id', 5)
    ->ttl(3600)
    ->issuer('my-app')
    ->audience('mobile')
    ->issue();

// 完整校验(验签 + 过期 + 黑名单 + 声明)
try {
    $payload = Jwt::parse($token);
    // 返回: ['sub' => 1, 'role' => 'admin', 'exp' => 1718256000, ...]
    echo $payload['sub'];   // 用户ID
    echo $payload['role'];  // 自定义声明
} catch (\wise\jwt\exception\TokenExpiredException $e) {
    // Token 已过期
} catch (\wise\jwt\exception\SignatureInvalidException $e) {
    // 签名无效
} catch (\wise\jwt\exception\BlacklistedException $e) {
    // 已被吊销
}

// 安全解析(失败返回 null,不抛异常)
$payload = Jwt::tryParse($token);
if ($payload === null) {
    // Token 无效
}

// 自动续签:在 refresh_ttl 窗口内,旧 Token 被吊销,返回新 Token
try {
    $newToken = Jwt::refresh($oldToken);
} catch (\Exception $e) {
    // 超出续签窗口,需重新登录
}

Jwt::revoke($token);

// 检查是否已吊销
$revoked = Jwt::isRevoked($jti);

// route/api.php
use wise\jwt\middleware\JwtAuth;

Route::group('api', function () {
    Route::get('profile', 'api.User/profile');
    Route::post('order', 'api.Order/create');
})->middleware(JwtAuth::class);

class UserController
{
    public function profile()
    {
        // 在控制器中获取 payload 的两种方式
        $payload = request()->jwtPayload;
        // 或
        $userId = request()->jwtPayload['sub'];
    }
}

// 在配置中定义提取器链
// 优先从 Header 提取,其次 Cookie,最后 Query
use wise\jwt\extractor\ChainExtractor;
use wise\jwt\extractor\BearerHeaderExtractor;
use wise\jwt\extractor\CookieExtractor;
use wise\jwt\extractor\QueryExtractor;

$extractor = new ChainExtractor([
    new BearerHeaderExtractor(),
    new CookieExtractor('access_token'),
    new QueryExtractor('token'),
]);

// app/event.php
return [
    'listen' => [
        \wise\jwt\event\TokenIssued::class => [
            \app\listener\LoginHistory::class,
        ],
        \wise\jwt\event\TokenRevoked::class => [
            \app\listener\LogoutCleanup::class,
        ],
        \wise\jwt\event\TokenInvalid::class => [
            \app\listener\SuspiciousActivity::class,
        ],
    ],
];
bash
php think wise:jwt:publish