完善JWT认证机制
This commit is contained in:
parent
463487b939
commit
779237afcd
@ -7,11 +7,14 @@ namespace App\Controller\PunchCard\User;
|
||||
use App\Controller\BaseController;
|
||||
use App\JsonRpc\PunchCardSystemExternalServiceInterface;
|
||||
use App\JsonRpc\UserExternalServiceInterface;
|
||||
use App\Middleware\AuthMiddleware;
|
||||
use Hyperf\Di\Annotation\Inject;
|
||||
use Hyperf\HttpServer\Annotation\Controller;
|
||||
use Hyperf\HttpServer\Annotation\GetMapping;
|
||||
use Hyperf\HttpServer\Annotation\Middleware;
|
||||
use Hyperf\HttpServer\Annotation\PostMapping;
|
||||
|
||||
#[Middleware(AuthMiddleware::class)]
|
||||
#[Controller(prefix: "kq")]
|
||||
class UserController extends BaseController
|
||||
{
|
||||
@ -39,8 +42,8 @@ class UserController extends BaseController
|
||||
#[GetMapping(path: "user/information")]
|
||||
public function information() : array
|
||||
{
|
||||
$openid = $this->request->input('openid', '');
|
||||
return $this->getServiceResult($this->userExternalService->getUserInfo($openid, [
|
||||
$user = $this->request->getAttribute('AuthUser');
|
||||
return $this->getServiceResult($this->userExternalService->getUserInfo($user['openid'], [
|
||||
'user_name',
|
||||
'user_phone',
|
||||
]));
|
||||
@ -77,7 +80,8 @@ class UserController extends BaseController
|
||||
#[PostMapping(path: "user/save_feedback")]
|
||||
public function saveFeedback() : array
|
||||
{
|
||||
return $this->getServiceResult($this->punchCardSystemExternalService->saveFeedback($this->request));
|
||||
$user = $this->request->getAttribute('AuthUser');
|
||||
return $this->getServiceResult($this->punchCardSystemExternalService->saveFeedback($this->request, $user['user_id']));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -101,4 +105,15 @@ class UserController extends BaseController
|
||||
{
|
||||
return $this->getServiceResult($this->userExternalService->addEmergencyContact($this->request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试打印JWT认证信息
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
#[GetMapping(path: "user/test")]
|
||||
public function test() : array
|
||||
{
|
||||
return $this->request->getAttribute('AuthUser');
|
||||
}
|
||||
}
|
||||
|
@ -6,6 +6,7 @@ namespace App\Controller;
|
||||
|
||||
use App\Exception\BusinessException;
|
||||
use App\JsonRpc\UserExternalServiceInterface;
|
||||
use App\Service\User\WechatAuthService;
|
||||
use Hyperf\Di\Annotation\Inject;
|
||||
use Hyperf\HttpServer\Annotation\AutoController;
|
||||
use Hyperf\Utils\Collection;
|
||||
@ -28,7 +29,7 @@ class TestController extends BaseController
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function index()
|
||||
public function index() : array
|
||||
{
|
||||
$data['user_id'] = 'test';
|
||||
return $data;
|
||||
@ -39,7 +40,7 @@ class TestController extends BaseController
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function empty()
|
||||
public function empty() : void
|
||||
{}
|
||||
|
||||
/**
|
||||
@ -47,7 +48,7 @@ class TestController extends BaseController
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function error()
|
||||
public function error(): mixed
|
||||
{
|
||||
throw new BusinessException(500, 'error');
|
||||
}
|
||||
@ -57,7 +58,7 @@ class TestController extends BaseController
|
||||
*
|
||||
* @return Paginator
|
||||
*/
|
||||
public function page()
|
||||
public function page() : Paginator
|
||||
{
|
||||
$currentPage = (int) $this->request->input('page', 1);
|
||||
$perPage = (int) $this->request->input('per_page', 2);
|
||||
@ -74,4 +75,22 @@ class TestController extends BaseController
|
||||
|
||||
return new Paginator($users, $perPage, $currentPage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取token(用于测试)
|
||||
*
|
||||
* @param WechatAuthService $wechatAuthService
|
||||
* @return array
|
||||
*/
|
||||
public function token(WechatAuthService $wechatAuthService) : array
|
||||
{
|
||||
$openid = $this->request->input('openid', '1111111');
|
||||
$user = $this->getServiceResult($this->userService->getUserInfo($openid, ['user_id', 'user_nickname']));
|
||||
|
||||
if (!empty($user)) {
|
||||
return $wechatAuthService->getToken($user['user_id'], $user['user_nickname'], $openid);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
@ -31,6 +31,6 @@ class PunchCardSystemExternalServiceConsumer extends AbstractServiceClient imple
|
||||
*/
|
||||
public function saveFeedback(RequestInterface $request) : array
|
||||
{
|
||||
return $this->__request(__FUNCTION__, $request->all());
|
||||
return $this->__request(__FUNCTION__, [...$request->all(), ...['user_id' => $request->getAttribute('AuthUser')['user_id']]]);
|
||||
}
|
||||
}
|
53
app/Middleware/AuthMiddleware.php
Normal file
53
app/Middleware/AuthMiddleware.php
Normal file
@ -0,0 +1,53 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
@ -81,14 +81,25 @@ class WechatAuthService
|
||||
throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL);
|
||||
}
|
||||
|
||||
$user_data = [
|
||||
'user_id' => $res['data']['user']['user_id'],
|
||||
'nickname' => $res['data']['user']['user_nickname'],
|
||||
'openid' => $res['data']['user']['user_openid']
|
||||
];
|
||||
return $this->getToken($res['data']['user']['user_id'], $res['data']['user']['user_nickname'], $res['data']['user']['user_openid']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取JWT认证token
|
||||
*
|
||||
* @param int $user_id
|
||||
* @param string $nickname
|
||||
* @param string $openid
|
||||
* @return array
|
||||
*/
|
||||
public function getToken(int $user_id, string $nickname, string $openid)
|
||||
{
|
||||
try {
|
||||
$token = $this->jwt->getToken('default', $user_data);
|
||||
$token = $this->jwt->getToken('default', [
|
||||
'user_id' => $user_id,
|
||||
'nickname' => $nickname,
|
||||
'openid' => $openid
|
||||
]);
|
||||
} catch (InvalidArgumentException) {
|
||||
// TODO 记录日志
|
||||
throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL);
|
||||
|
@ -18,7 +18,6 @@ return [
|
||||
*/
|
||||
'no_check_route' => [
|
||||
// ["**", "/**"],
|
||||
["**", "/kq/auth/code2OpenID"]
|
||||
],
|
||||
|
||||
'login_type' => env('JWT_LOGIN_TYPE', 'mpop'), // 登录方式,sso为单点登录,同一个用户只能登录一个端,mpop为多点登录
|
||||
|
@ -11,6 +11,5 @@ declare(strict_types=1);
|
||||
*/
|
||||
return [
|
||||
'http' => [
|
||||
Phper666\JWTAuth\Middleware\JWTAuthDefaultSceneMiddleware::class
|
||||
],
|
||||
];
|
||||
|
Loading…
Reference in New Issue
Block a user