Slim 4 中的路由中间件不会停止调用路由中的可调用对象

2023-11-24

我在 Slim4 中的授权中间件上遇到了困难。这是我的代码:

$app = AppFactory::create();
$app->add(new Authentication());

$app->group('/providers', function(RouteCollectorProxy $group){
    $group->get('/', 'Project\Controller\ProviderController:get');
})->add(new SuperuserAuthorization());

身份验证中间件检查用户并且工作正常。

方法get在 ProviderController 中是

public function get(Request $request, Response $response): Response{
    $payload = [];
    foreach(Provider::all() as $provider){
        $payload[] = [
            'id' => $provider->id,
            'name' => $provider->name,
        ];
    }
    $response->getBody()->write(json_encode($payload));
    return $response;
}

超级用户授权看起来像这样

class SuperuserAuthorization{
    public function __invoke(Request $request, RequestHandler $handler): Response{
        $response = $handler->handle($request);
        $authorization = explode(" ", $request->getHeader('Authorization')[0]);
        $user = User::getUserByApiKey($authorization[1]);
        if(! Role::isSuperuser($user)){
            return $response->withStatus(403);//Forbidden
        }
        return $response;
    }
}

问题是,即使用户不是超级用户,应用程序也会继续执行。结果我得到了所有提供者的 json 和 http 代码 403 :/

路由中间件不应该阻止请求进入应用程序并立即返回 403 吗?

我知道我可以创建状态为 403 的新空响应,因此数据不会出来,但重点是请求永远不应该超出这个中间件,我是对的还是我只是误解了这里的某些内容......

任何帮助将不胜感激 :)

- - - - - - - 解决方案 - - - - - - - -

感谢@Nima 我解决了它。中间件更新版本为:

class SuperuserAuthorization{
    public function __invoke(Request $request, RequestHandler $handler): Response{
        $authorization = explode(" ", $request->getHeader('Authorization')[0]);
        $user = User::getUserByApiKey($authorization[1]);
        if(! Role::isSuperuser($user)){
            $response = new Response();
            return $response->withStatus(403);//Forbidden
        }
        return $handler->handle($request);
    }
}

路由中间件不应该阻止请求进入应用程序并立即返回 403 吗?

修身4用PSR-15兼容的中间件。有好的example说明如何在 PSR-15 元文档中实现授权中间件。你需要避免打电话$handler->handle($request)如果您不希望进一步处理该请求。

正如您在示例中看到的,如果请求未经授权,则响应与返回值不同$handler->handle($request)被返回。这意味着你的观点是:

我知道我可以创建状态为 403 的新空响应,因此数据不会出来,但重点是请求永远不应该超出这个中间件

在某种程度上是正确的,但是you应通过返回适当的响应来阻止请求进一步发展before调用处理程序,或抛出异常并让错误处理程序处理它。

这是一个简单的中间件,它随机授权一些请求并为其他请求抛出异常:

$app->group('/protected', function($group){
    $group->get('/', function($request, $response){
        $response->getBody()->write('Some protected response...');
        return $response;
    });
})->add(function($request, $handler){
    // randomly authorize/reject requests
    if(rand() % 2) {
        // Instead of throwing an exception, you can return an appropriate response
        throw new \Slim\Exception\HttpForbiddenException($request);
    }
    $response = $handler->handle($request);
    $response->getBody()->write('(this request was authorized by the middleware)');
    return $response;
});

要查看不同的回复,请访问/protected/路径几次(记住中间件是随机行为的)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Slim 4 中的路由中间件不会停止调用路由中的可调用对象 的相关文章

随机推荐