如何在Laravel Lighthouse中检查查询的深度和复杂度
P粉419164700
P粉419164700 2023-08-28 21:26:41
0
1
639
<p>在将lighthouse部署到生产服务器之前,我会检查安全性(https://www.howtographql.com/advanced/4-security/)。因此,我决定检查查询深度和查询复杂度。</p> <p>在lighthouse文档中,他们提到了<code>config/lighthouse.php</code>。</p> <pre class="brush:php;toolbar:false;">/* |-------------------------------------------------------------------------- | Security |-------------------------------------------------------------------------- | | 控制Lighthouse处理与安全相关的查询验证。 | 详细阅读:https://webonyx.github.io/graphql-php/security/ | */ 'security' => [ 'max_query_complexity' => \GraphQL\Validator\Rules\QueryComplexity::DISABLED, 'max_query_depth' => \GraphQL\Validator\Rules\QueryDepth::DISABLED, 'disable_introspection' => \GraphQL\Validator\Rules\DisableIntrospection::DISABLED, ], </pre> <p>并且推荐阅读https://webonyx.github.io/graphql-php/security/。</p> <p>在这个链接中,他们给出了一些示例:</p> <pre class="brush:php;toolbar:false;">use GraphQL\GraphQL; use GraphQL\Validator\Rules\QueryComplexity; use GraphQL\Validator\DocumentValidator; $rule = new QueryComplexity($maxQueryComplexity = 100); DocumentValidator::addRule($rule); GraphQL::executeQuery(/*...*/); </pre> <pre class="brush:php;toolbar:false;">use GraphQL\GraphQL; use GraphQL\Validator\Rules\QueryDepth; use GraphQL\Validator\DocumentValidator; $rule = new QueryDepth($maxDepth = 10); DocumentValidator::addRule($rule); GraphQL::executeQuery(/*...*/); </pre> <p>但是如何在lighthouse中应用这些呢?</p> <p>首先,我将这些代码写入了<code>ExampleQuery.php(php artisan lighthouse:query ExampleQuery)</code>。</p> <pre class="brush:php;toolbar:false;">final class ExampleQuery { public function __invoke(_, array $args) { $rule = new QueryComplexity(2); DocumentValidator::addRule($rule); $rule2 = new QueryDepth(2); DocumentValidator::addRule($rule2); return [ ... ]; } } </pre> <p>但是这样无法捕获任何问题。</p> <p>我认为lighthouse在<code>vendor/nuwave/.../GraphQLController.php</code>中启动,所以我无法执行<code>GraphQL::executeQuery(/*...*/);</code></p> <p><code>@complexity</code>指令也不起作用,<code>@complexity(resolver: "App\\Security\\ComplexityAnalyzer@userPosts")</code>不会调用userPosts函数。</p> <pre class="brush:php;toolbar:false;">class ComplexityAnalyzer { public function userPosts(int $childrenComplexity, array $args): int // not called { $postComplexity = $args['includeFullText'] ? 3 : 2; \Log::Debug($postComplexity); // not called return $childrenComplexity * $postComplexity; } } </pre> <p>我错过了什么?请帮助我睡个舒服觉。</p>
P粉419164700
P粉419164700

全部回复(1)
P粉717595985

它已经实现了,你只需要设置值。

'security' => [
        'max_query_complexity' => 100,
        'max_query_depth' => 10,
    ],

复杂度分数计算可以使用@complexity指令对每个字段进行修改。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板