53 lines
1.7 KiB
PHP
53 lines
1.7 KiB
PHP
|
<?php
|
||
|
|
||
|
declare(strict_types=1);
|
||
|
|
||
|
namespace App\Middleware;
|
||
|
|
||
|
use App\Constants\ErrorCode;
|
||
|
use Hyperf\Context\Context;
|
||
|
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
|
||
|
use Phper666\JWTAuth\Exception\JWTException;
|
||
|
use Phper666\JWTAuth\Util\JWTUtil;
|
||
|
use Psr\Http\Message\ResponseInterface;
|
||
|
use Psr\Http\Message\ServerRequestInterface;
|
||
|
use Psr\Http\Server\MiddlewareInterface;
|
||
|
use Psr\Http\Server\RequestHandlerInterface;
|
||
|
use Phper666\JWTAuth\JWT;
|
||
|
use Phper666\JWTAuth\Exception\TokenValidException;
|
||
|
|
||
|
/**
|
||
|
* jwt token 校验的中间件,校验场景是否一致
|
||
|
*/
|
||
|
class AuthMiddleware implements MiddlewareInterface
|
||
|
{
|
||
|
public function __construct(protected HttpResponse $response, protected JWT $jwt)
|
||
|
{
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @param ServerRequestInterface $request
|
||
|
* @param RequestHandlerInterface $handler
|
||
|
* @return ResponseInterface
|
||
|
* @throws \Psr\SimpleCache\InvalidArgumentException
|
||
|
* @throws \Throwable
|
||
|
*/
|
||
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||
|
{
|
||
|
$token = $request->getHeaderLine('Authorization') ?? '';
|
||
|
if ($token === "") {
|
||
|
throw new JWTException('Missing token', ErrorCode::COMMON_ERROR);
|
||
|
}
|
||
|
|
||
|
$token = JWTUtil::handleToken($token);
|
||
|
if ($token !== false && $this->jwt->verifyTokenAndScene('default', $token)) {
|
||
|
// 封装认证用户信息
|
||
|
$request = $request->withAttribute('AuthUser', JWTUtil::getParserData($request));
|
||
|
Context::set(ServerRequestInterface::class, $request);
|
||
|
|
||
|
return $handler->handle($request);
|
||
|
}
|
||
|
|
||
|
throw new TokenValidException('Token authentication does not pass', ErrorCode::COMMON_ERROR);
|
||
|
}
|
||
|
}
|