webman_ad/app/middleware/JwtLocal.php
2025-01-06 14:47:09 +08:00

80 lines
2.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\middleware;
use Webman\MiddlewareInterface;
use Webman\Http\Request;
use Webman\Http\Response;
use Firebase\JWT\JWT as FJWT;
use Firebase\JWT\Key;
use Exception;
class JwtLocal implements MiddlewareInterface
{
// 签名密钥
private const SIGNING_KEY = '83OP5jf43875jK7';
public function process(Request $request, callable $handler): Response
{
// 获取 Authorization 头
$authorization = $request->header('Authorization', '');
if (empty($authorization) || strpos($authorization, 'Bearer ') !== 0) {
return Json([
'code' => 1,
'msg' => '缺少 Authorization 头或格式无效',
'data' => []
]);
}
// 提取 JWT token
$jwtToken = substr($authorization, 7);
try {
// 使用 firebase/php-jwt 解码并验证 JWT
// $decoded = FJWT::decode($jwtToken, new Key(self::SIGNING_KEY, 'HS512'), $headers = new stdClass()); // 使用 HMAC-SHA512 算法进行验证
$decoded = FJWT::decode($jwtToken, new Key(self::SIGNING_KEY, 'HS512'));
// 将解码后的数据(即 claims存入请求对象后续可以访问
$request->jwtClaims = (array)$decoded;
// 验证 JWT Token
// dump((array)$decoded);
// return Json([
// 'code' => 0,
// 'msg' => 'JWT 验证成功',
// 'data' => []
// ]);
// 继续处理请求
return $handler($request);
} catch (Exception $e) {
return Json([
'code' => 1,
'msg' => $e->getMessage(),
'data' => []
]);
// return response(['code' => 1, 'msg' => 'JWT 验证失败: ' . $e->getMessage()], 200);
}
}
private function getErrorMessage($result)
{
switch ($result) {
case 'JWT_VERIFY_BAD_FORMAT':
return '无效的 token 格式';
case 'JWT_VERIFY_SIGN_FAILED':
return 'token 签名无效';
case 'JWT_VERIFY_EXPIRED':
return 'token 已过期';
case 'JWT_VERIFY_REVOKED':
return 'token 已被撤销';
case 'JWT_VERSION_LOW':
return 'token 版本过低';
default:
return '未知错误';
}
}
}