【五一创作】Hyperf3.0创建中间件并使用JWT鉴权
    		       		warning:
    		            这篇文章距离上次修改已过451天,其中的内容可能已经有所变动。
    		        
        		                
                
<?php
declare(strict_types=1);
 
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;
use Hyperf\HttpServer\Contract\MiddlewareInterface;
use Firebase\JWT\JWT;
 
class JwtMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;
 
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }
 
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);
        $jwt = $request->header('authorization');
        if (empty($jwt)) {
            return $response->withStatus(401)->withBody(json_encode(['code' => 401, 'msg' => 'Token不能为空']));
        }
        try {
            JWT::decode($jwt, 'your_secret_key', ['HS256']);
        } catch (\Exception $e) {
            return $response->withStatus(401)->withBody(json_encode(['code' => 401, 'msg' => 'Token验证失败']));
        }
        return $response;
    }
}这段代码实现了一个JWT鉴权的中间件,它检查HTTP请求头中的authorization字段,并使用JWT库对令牌进行解析和验证。如果验证失败,则返回401未授权的HTTP状态码和相应的错误信息。这个例子展示了如何在Hyperf框架中创建一个简单的中间件,并在HTTP请求处理管道中使用它来实现身份验证逻辑。
评论已关闭