You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.4 KiB
PHP
82 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Services\JwtService;
|
|
use Closure;
|
|
use Firebase\JWT\ExpiredException;
|
|
use Firebase\JWT\SignatureInvalidException;
|
|
use InvalidArgumentException;
|
|
use Illuminate\Http\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class CheckToken
|
|
{
|
|
protected $jwtService;
|
|
|
|
/**
|
|
* 构造函数注入JwtService
|
|
*/
|
|
public function __construct(JwtService $jwtService)
|
|
{
|
|
$this->jwtService = $jwtService;
|
|
}
|
|
|
|
/**
|
|
* Handle an incoming request.
|
|
*
|
|
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
*/
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$authHeader = $request->header('Authorization');
|
|
|
|
if (!$authHeader) {
|
|
return response()->json([
|
|
'code' => 401,
|
|
'message' => 'Authorization header is required'
|
|
], 401);
|
|
}
|
|
|
|
$token = str_replace('Bearer ', '', $authHeader);
|
|
|
|
if (!$token) {
|
|
return response()->json([
|
|
'code' => 401,
|
|
'message' => 'Token is required'
|
|
], 401);
|
|
}
|
|
|
|
try {
|
|
// 直接调用JwtService的verifyToken方法
|
|
$user = $this->jwtService->verifyToken($token);
|
|
|
|
// 将用户信息存入请求属性
|
|
$request->attributes->set('payload', $user);
|
|
|
|
return $next($request);
|
|
} catch (ExpiredException $e) {
|
|
return response()->json([
|
|
'code' => 401,
|
|
'message' => 'Token已过期'
|
|
], 401)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
|
|
} catch (SignatureInvalidException $e) {
|
|
return response()->json([
|
|
'code' => 400,
|
|
'message' => 'Token签名无效'
|
|
], 400)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
|
|
} catch (InvalidArgumentException $e) {
|
|
return response()->json([
|
|
'code' => 400,
|
|
'message' => 'Token格式错误'
|
|
], 400)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
|
|
} catch (\Exception $e) {
|
|
return response()->json([
|
|
'code' => 400,
|
|
'message' => 'Invalid token',
|
|
'error' => $e->getMessage()
|
|
], 400)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
|
|
}
|
|
}
|
|
}
|