You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

199 lines
5.1 KiB

<?php
declare(strict_types=1);
/**
* JwtService.php
* Created by PhpStorm.
* Date: 2026/10/17
* Time: 09:40
* Author: qian.guo
* E-mail: yiyezhiqiutel@gmail.com
*/
namespace app\service;
use app\BusinessException;
/**
* JWT 签发与校验服务(HS256,自实现)
* 设计说明:
* - 不引第三方库:只有一个算法、一个密钥,代码不到百行
* 少一个 composer 依赖就少一次版本升级与安全公告的维护成本
* 将来若需要 RS256 或多签发方,再换 firebase/php-jwt
* - 载荷只带 sub(账号ID)与 jti,不带 openid
* token 会被前端持有并在网络上来回传,不应携带身份标识
* - jti 供将来服务端强制下线用(黑名单需 Redis,尚未接入)
* - 状态码一律取 config('code.*'),不要硬编码数字与中文
*/
class JwtService
{
// 签名密钥
private $secret;
// 有效期秒数
private $ttl;
public function __construct($secret, $ttl = 604800)
{
$secret = (string) $secret;
// 短密钥可被暴力破解,签出去的 token 等于没签
if (strlen($secret) < 32) {
throw new BusinessException(
config('code.err.server_busy'),
'JWT_SECRET 长度不足 32 位,请检查 .env'
);
}
$this->secret = $secret;
$this->ttl = intval($ttl);
}
/**
* 签发 token
* createToken
* @param int $user_id 账号ID
* @param array $extra 额外载荷
* @return array 含 token / expires_at / expires_in
*/
public function createToken($user_id, $extra = [])
{
$now = time();
$exp = $now + $this->ttl;
$payload = $extra;
$payload['iss'] = 'zhunxin';
$payload['sub'] = $user_id;
$payload['iat'] = $now;
$payload['exp'] = $exp;
$payload['jti'] = bin2hex(random_bytes(8));
$data = [];
$data['token'] = $this->encodeToken($payload);
$data['expires_at'] = $exp;
$data['expires_in'] = $this->ttl;
return $data;
}
/**
* 校验 token
* checkToken
* @param string $token 待校验 token
* @return array 载荷
*/
public function checkToken($token)
{
$err_code = config('code.err.unauthed');
$err_msg = '登录已过期,请重新进入';
$parts = explode('.', (string) $token);
if (count($parts) !== 3) {
throw new BusinessException($err_code, $err_msg);
}
$head = $parts[0];
$body = $parts[1];
$sign = $parts[2];
$expected = $this->signTokenPart($head . '.' . $body);
// 定长比较,避免通过响应时间逐字节试探签名
if (!hash_equals($expected, $sign)) {
throw new BusinessException($err_code, $err_msg);
}
$payload = json_decode($this->decodeSegment($body), true);
if (!is_array($payload)) {
throw new BusinessException($err_code, $err_msg);
}
$exp = intval($payload['exp'] ?? 0);
if ($exp < time()) {
throw new BusinessException($err_code, $err_msg);
}
return $payload;
}
/**
* 校验 token(失败不抛异常)
* tryCheckToken
* @param string $token 待校验 token
* @return array 失败返回空数组
*/
public function tryCheckToken($token)
{
try {
return $this->checkToken($token);
} catch (\Throwable $e) {
return [];
}
}
/**
* 编码完整 token
* encodeToken
* @param array $payload 载荷
* @return string
*/
private function encodeToken($payload)
{
$head = $this->encodeSegment(['typ' => 'JWT', 'alg' => 'HS256']);
$body = $this->encodeSegment($payload);
return $head . '.' . $body . '.' . $this->signTokenPart($head . '.' . $body);
}
/**
* 生成签名
* signTokenPart
* @param string $data 待签名内容
* @return string
*/
private function signTokenPart($data)
{
return $this->encodeSegment(hash_hmac('sha256', $data, $this->secret, true));
}
/**
* base64url 编码
* encodeSegment
* @param mixed $data 数组或字符串
* @return string
*/
private function encodeSegment($data)
{
// 必须先判数组再转换:数组直接强转字符串会触发转换警告
if (is_array($data)) {
$raw = (string) json_encode($data, JSON_UNESCAPED_UNICODE);
} else {
$raw = (string) $data;
}
return rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');
}
/**
* base64url 解码
* decodeSegment
* @param string $data 编码内容
* @return string 失败返回空字符串
*/
private function decodeSegment($data)
{
$data = (string) $data;
$pad = strlen($data) % 4;
if ($pad > 0) {
$data .= str_repeat('=', 4 - $pad);
}
$decoded = base64_decode(strtr($data, '-_', '+/'), true);
if ($decoded === false) {
return '';
}
return $decoded;
}
}