Files
NewTicket/app/admin/middleware/Auth.php
2026-05-07 16:37:25 +08:00

32 lines
1.1 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\admin\middleware;
use thans\jwt\facade\JWTAuth;
use thans\jwt\exception\TokenExpiredException;
class Auth
{
public function handle($request, \Closure $next)
{
try {
// 1. 核心:必须先执行 auth(),它会自动从 Header 读取 Bearer Token 并验证
// 如果过期或非法,这里会直接抛出异常
$payload = JWTAuth::auth();
// $payload = JWTAuth::getPayload(); 这个是获取数据进行解码token
$request->login_user_id = (int)$payload['user_id'] ?? null;
$request->login_role = $payload['role'] ?? null;
return $next($request);
}catch (TokenExpiredException $e){
// 捕获token过期异常
return json(['code' => 401, 'msg' => '登录已过期,请重新登录'],401);
} catch (\Exception $e) {
// 如果报错,返回具体的错误信息,方便我们排查
return json(['code' => 400, 'msg' => '权限校验失败:' . $e->getMessage()], 400);
}
}
}