跳转到正文
wise-* 包教程 20 个可独立安装的 Composer 能力包:选包、装包、调用、扩展

JWT 令牌管理 wise-jwt

1 2026-11-25 23:02:34

令牌签发、校验、刷新、吊销,支持 10 种算法。它的定位是"引擎"——业务代码通常通过 wise\support\facade\JWT 或本包门面调用,而 wise-api、wise-auth 都建立在它之上。

安装

composer require wiseadmin/wise-jwt
php think vendor:publish
php think wise:jwt:key:generate --type=hmac
php think migrate:run          # 仅当黑名单驱动选 database 时才需要

extra.think.services 注册 JwtServiceProvider;配置发布为 config/wise-jwt.php。

10 种算法

HS256 / HS384 / HS512、RS256 / RS384 / RS512、ES256 / ES384 / ES512、EdDSA(Ed25519,需要 ext-sodium)。

配置关键项:default / algorithm、secret / secret_base64 / secret_file、private_key* / public_key*、issuer / audience、ttl = 7200、refresh_ttl = 1800、blacklist(cache / redis / database)、refresh_token、fingerprint、throttle、global_revoke、keys(kid 轮换)、token.extractors = ['bearer']、guards、auto_refresh、validation。

对称算法只需要 secret;非对称要私钥与公钥,且 kid 轮换依赖 keys 段。

Jwt 门面

use wise\jwt\facade\Jwt;

$token   = Jwt::issue($userId, ['role' => 'admin']);
$pair    = Jwt::issuePair($userId, ['role' => 'admin']);   // access + refresh
$payload = Jwt::parse($token);
$try     = Jwt::tryParse($token);                           // 失败返回 null,不抛
$new     = Jwt::refresh($oldToken);
Jwt::revoke($token);
Jwt::revokeAllBySubject($userId);
Jwt::isRevoked($jti);

其余:decode() / decodeHeader() / decodeFull()、revokeMany()、revokeByJti()、refreshAccessToken()、revokeRefreshToken()、getVersion()、builder()、shouldRefresh()、ttlOf()。

parse() 与 tryParse() 的差别是"要不要抛异常":中间件里用 tryParse() 更省事,业务校验里用 parse() 更容易定位失败原因。

密钥生成

php think wise:jwt:key:generate --type=hmac
php think wise:jwt:key:generate --type=rsa --bits=2048 --output

选项 --type=hmac|rsa|ec|eddsa(默认 hmac)、--bits、--output(直接输出 config 片段)。退出码 0 成功 / 1 参数非法或缺少扩展(如 EdDSA 缺 ext-sodium)。

配套命令:wise:jwt:decode(解出载荷看 sub/iat/exp)、wise:jwt:revoke(主动吊销)、wise:jwt:blacklist(黑名单管理)。

与 wise-support 的挂接

wise-jwt 在 boot() 里注册扩展点:

ExtPoint::register(ExtPoints::JWT_PROVIDER, 'wise-jwt', fn (?string $guard = null) => ...);

这是 wise\support\facade\JWT 能透明代理当前引擎的关键:

support\JWT::issue() → container('jwt') → JwtManager::__call()
→ ExtPoint('jwt.provider') → wise\jwt\Jwt

所以业务代码两种写法等价。引擎被停用时,support\JWT 会表现为"未登录"而不是报错——排查 JWT 问题时先确认扩展点有没有活跃实现。

三个容易搞错的认知

一、"多机部署用默认 cache 黑名单就行"。 缓存不共享等于没吊销,多机必须换 redis 或 database 驱动。
二、"revoke() 会让该用户所有设备下线"。 它只吊销单个 jti,全下用 revokeAllBySubject()。
三、"换了算法只改配置即可"。 非对称还要配公私钥,EdDSA 还要扩展;改算法后旧令牌全部失效(密钥或算法不匹配)。

自查:wise:jwt:key:generate --output 生成的配置能直接粘进 config/wise-jwt.php;签发后 parse() 能拿回 sub/iat/exp;revoke() 后 isRevoked($jti) 为 true。框架侧概念见JWT 令牌。

这篇文档对您有帮助吗?

相关文档