企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 安装扩展库 composer require lindelius/php-jwt ### 添加中间件 就叫 Jwt.php 吧 代码大致如下 ~~~ <?php declare(strict_types=1); namespace App\Middleware; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse; use Hyperf\Utils\Context; use Lindelius\JWT\StandardJWT; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; class Jwt implements MiddlewareInterface { /** * @var ContainerInterface */ protected $container; protected $response; protected $request; public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request) { $this->container = $container; $this->response = $response; $this->request = $request; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $headers = $request->getHeaders(); if (empty($headers['token'])) { return $this->response->json( [ 'code' => 0, 'data' => [ 'error' => 'token不能为空', ], ] )->withStatus(401); } // 验证token $token = $headers['token'][0]; $jwt = new StandardJWT(); try { $decodedJwt = $jwt::decode($token); $payload = $decodedJwt->getPayload(); $userId = $payload['sub']; $request = $request->withAttribute('userid', $userId); // 添加属性 Context::set(ServerRequestInterface::class, $request); // 设置属性 } catch (\Exception $exception) { return $this->response->json( [ 'code' => $exception->getCode(), 'data' => [ 'error' => $exception->getMessage() ], ] )->withStatus(401); } return $handler->handle($request); } } ~~~ ### 控制器中注入jwt中间件 ~~~ <?php namespace App\Controller; use Hyperf\HttpServer\Annotation\AutoController; use Hyperf\HttpServer\Annotation\Middleware; use Lindelius\JWT\StandardJWT; use App\Middleware\Jwt; /** * @AutoController() * @Middleware(Jwt::class) */ class Home extends AbstractController { protected $userid; public function index() { $arr = $this->request->getAttributes(); // 获取属性 return $arr['userid']; } } ~~~