hyperf-chat/app/Middleware/JWTAuthMiddleware.php

74 lines
1.8 KiB
PHP
Raw Normal View History

2020-11-14 17:37:55 +08:00
<?php
namespace App\Middleware;
2020-11-24 23:23:12 +08:00
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
2020-11-14 17:37:55 +08:00
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
2020-11-24 23:23:12 +08:00
use Psr\Http\Server\MiddlewareInterface;
2020-11-14 17:37:55 +08:00
use Psr\Http\Server\RequestHandlerInterface;
2020-11-24 23:23:12 +08:00
use Phper666\JWTAuth\JWT;
use Phper666\JWTAuth\Util\JWTUtil;
2020-11-14 17:37:55 +08:00
2020-11-24 23:23:12 +08:00
/**
* Http Token 授权验证中间件
*
* @package App\Middleware
*/
class JWTAuthMiddleware implements MiddlewareInterface
2020-11-14 17:37:55 +08:00
{
/**
2020-11-24 23:23:12 +08:00
* @var RequestInterface
*/
protected $request;
/**
* @var HttpResponse
*/
protected $response;
/**
* @var JWT
2020-11-14 17:37:55 +08:00
*/
2020-11-24 23:23:12 +08:00
protected $jwt;
public function __construct(HttpResponse $response, RequestInterface $request, JWT $jwt)
{
$this->response = $response;
$this->request = $request;
$this->jwt = $jwt;
}
2020-11-14 17:37:55 +08:00
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
2020-12-01 13:54:40 +08:00
$isValidToken = false;
2020-11-24 23:23:12 +08:00
// 获取请求token
2020-12-01 13:54:40 +08:00
$token = $request->getHeaderLine('Authorization');
if (empty($token)) {
$token = $this->request->input('token', '');
}
2020-11-24 23:23:12 +08:00
if (!empty($token)) {
2020-11-14 17:37:55 +08:00
try {
$token = JWTUtil::handleToken($token);
if ($token !== false && $this->jwt->checkToken($token)) {
$isValidToken = true;
}
2020-11-24 23:23:12 +08:00
} catch (\Exception $e) {
$isValidToken = false;
2020-11-14 17:37:55 +08:00
}
}
2020-11-24 23:23:12 +08:00
if (!$isValidToken) {
return $this->response->withStatus(401)->json([
'code' => 401,
'message' => 'Token authentication does not pass',
]);
2020-11-14 17:37:55 +08:00
}
2020-11-24 23:23:12 +08:00
return $handler->handle($request);
2020-11-14 17:37:55 +08:00
}
}