如何在Laravel Lighthouse中檢查查詢的深度和複雜度
P粉419164700
P粉419164700 2023-08-28 21:26:41
0
1
640
<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指令對每個欄位進行修改。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板