Skip to content

Commit

Permalink
Add authentication middleware and exception
Browse files Browse the repository at this point in the history
Added new files AuthMiddleware.php and AuthException.php to implement JWT-based authentication middleware and custom AuthException. Class AuthException will handle unauthorized access. Authentication was integrated with the AuthMiddleware into the signOut method in UserController.php. Also updated 'no_check_route' and 'login_type' configurations in jwt.php to support the changes. This commit ensures secure access to sensitive routes by validating JWT token.
  • Loading branch information
AuroraYolo committed Aug 30, 2023
1 parent c98f8aa commit 712badd
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 2 deletions.
7 changes: 7 additions & 0 deletions app/Controller/Sys/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@
use App\Controller\AbstractController;
use App\Exception\BusinessException;
use App\Logic\UserLogic;
use App\Middleware\Auth\AuthMiddleware;
use App\Request\UserRequest;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;

#[Controller(prefix: 'sys/user')]
class UserController extends AbstractController
Expand All @@ -31,6 +34,9 @@ public function register()
{
}

/**
* @throws InvalidArgumentException
*/
#[PostMapping(path: 'signIn')]
public function login(UserRequest $request): ResponseInterface
{
Expand All @@ -47,6 +53,7 @@ public function login(UserRequest $request): ResponseInterface
}

#[PostMapping(path: 'signOut')]
#[Middleware(middleware: AuthMiddleware::class)]
public function signOut()
{
}
Expand Down
24 changes: 24 additions & 0 deletions app/Exception/AuthException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);
/**
* This file is part of Cloud-Admin project.
*
* @link https://www.cloud-admin.jayjay.cn
* @document https://wiki.cloud-admin.jayjay.cn
* @license https://github.com/swow-cloud/swow-admin/blob/master/LICENSE
*/

namespace App\Exception;

use Hyperf\HttpMessage\Exception\HttpException;
use Swow\Http\Status;
use Throwable;

class AuthException extends HttpException
{
public function __construct(int $code = Status::UNAUTHORIZED, string $message = null, ?Throwable $previous = null)
{
parent::__construct($code, $message, $previous);
}
}
56 changes: 56 additions & 0 deletions app/Middleware/Auth/AuthMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);
/**
* This file is part of Cloud-Admin project.
*
* @link https://www.cloud-admin.jayjay.cn
* @document https://wiki.cloud-admin.jayjay.cn
* @license https://github.com/swow-cloud/swow-admin/blob/master/LICENSE
*/

namespace App\Middleware\Auth;

use App\Exception\AuthException;
use App\Kernel\Http\Response;
use Hyperf\Di\Annotation\Inject;
use Phper666\JWTAuth\JWT;
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 Swow\Http\Status;

class AuthMiddleware implements MiddlewareInterface
{
#[Inject]
protected Response $response;

#[Inject]
protected JWT $jwt;

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// 判断是否为noCheckRoute
$path = $request->getUri()->getPath();
$method = $request->getMethod();
if ($this->jwt->matchRoute(null, $method, $path)) {
return $handler->handle($request);
}

$token = $request->getHeaderLine('Authorization') ?? '';

if ($token === '') {
return $this->response->handleException(new AuthException(Status::BAD_REQUEST));
}

$token = JWTUtil::handleToken($token);

if ($token !== false && $this->jwt->verifyToken($token)) {
return $handler->handle($request);
}

return $this->response->handleException(new AuthException(Status::UNAUTHORIZED, 'Token authentication does not pass'));
}
}
7 changes: 5 additions & 2 deletions config/autoload/jwt.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@
* 正则写法:["**", "/api/{name:.+}"] 支持模块化不做jwt token的校验,例如:/api/login/login
*/
'no_check_route' => [
['**', '/**'],
// [
// '**',
// '/**'
// ],
],

'login_type' => env('JWT_LOGIN_TYPE', 'mpop'), // 登录方式,sso为单点登录,同一个用户只能登录一个端,mpop为多点登录
'login_type' => \Hyperf\Support\env('JWT_LOGIN_TYPE', 'mpop'), // 登录方式,sso为单点登录,同一个用户只能登录一个端,mpop为多点登录

/*
* 单点登录自定义数据中必须存在uid的键值,这个key你可以自行定义,只要自定义数据中存在该键即可
Expand Down

0 comments on commit 712badd

Please sign in to comment.