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; } }