在 Hyperf 框架中,鉴权可以通过中间件和注解两种方式进行详细解释。
- 中间件鉴权:
中间件是 Hyperf 框架提供的一种常用的鉴权方式。你可以创建一个中间件来完成鉴权逻辑,并将其应用到需要进行权限控制的路由或控制器上。下面是一个简单的示例:
首先,创建一个鉴权中间件 AuthMiddleware
:
php"><?php
namespace App\Middleware;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
class AuthMiddleware
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function process(RequestInterface $request, callable $handler): HttpResponse
{
// 鉴权逻辑
// 判断用户是否登录,或者权限是否满足等等
if (! $this->checkAuth()) {
// 鉴权失败,返回未授权错误
return $this->container->get(HttpResponse::class)->json([
'code' => 401,
'message' => 'Unauthorized',
]);
}
// 鉴权通过,继续处理请求
return $handler($request);
}
private function checkAuth()
{
// 在这里进行具体的鉴权逻辑判断
// 根据业务需求,判断用户是否有权限访问资源等等
return true; // 鉴权通过返回 true,鉴权失败返回 false
}
}
然后,将中间件注册到全局中间件或指定路由:
在 config/autoload/middlewares.php
文件中添加以下代码:
return [
'http' => [
// ... 其他中间件
\App\Middleware\AuthMiddleware::class,
],
];
这样,AuthMiddleware
就会应用到所有的 HTTP 请求中。
如果你只想对指定的路由应用鉴权中间件,你可以在路由配置文件(如 config/routes.php
)中使用 ->middleware()
方法:
use App\Controller\HomeController;
Router::get('/', [HomeController::class, 'index'])->middleware(\App\Middleware\AuthMiddleware::class);
- 注解鉴权:
除了中间件之外,Hyperf 还提供了基于注解的鉴权方式。通过在控制器方法上添加注解来实现鉴权逻辑。下面是一个简单的示例:
首先,创建一个自定义注解 Auth
:
<?php
namespace App\Annotation;
use Hyperf\Di\Annotation\AbstractAnnotation;
/**
* @Annotation
* @Target({"METHOD"})
*/
class Auth extends AbstractAnnotation
{
}
然后,在需要进行鉴权的控制器方法上使用 @Auth
注解:
<?php
namespace App\Controller;
use App\Annotation\Auth;
class HomeController extends AbstractController
{
/**
* @Auth
*/
public function index()
{
// 在这里编写正常访问的逻辑
}
}
接下来,创建一个自定义切面类 AuthAspect
来处理鉴权逻辑:
<?php
namespace App\Aspect;
use App\Annotation\Auth;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Psr\Log\LoggerInterface;
/**
* @Aspect
*/
class AuthAspect
{
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
// 获取方法上的注解
/** @var Auth $authAnnotation */
$authAnnotation = $proceedingJoinPoint->getAnnotationMetadata()->method[Auth::class] ?? null;
// 进行鉴权逻辑
if ($authAnnotation) {
// 根据业务需求进行权限校验
if (! $this->checkAuth()) {
return [
'code' => 401,
'message' => 'Unauthorized',
];
}
}
return $proceedingJoinPoint->process();
}
private function checkAuth()
{
// 在这里进行具体的鉴权逻辑判断
// 根据业务需求,判断用户是否有权限访问资源等等
return true; // 鉴权通过返回 true,鉴权失败返回 false
}
}
最后,配置切面类 AuthAspect
:
在 config/autoload/aspects.php
文件中添加以下代码:
return [
App\Aspect\AuthAspect::class,
];
这样,当访问 HomeController
中带有 @Auth
注解的方法时,会触发 AuthAspect
类中的 process
方法,进行鉴权逻辑判断。
以上是 Hyperf 框架中鉴权的两种常用方式:中间件和注解。你可以根据项目需求选择合适的方式实现鉴权功能。