在将lighthouse部署到生产服务器之前,我会检查安全性(https://www.howtographql.com/advanced/4-security/)。因此,我决定检查查询深度和查询复杂度。
在lighthouse文档中,他们提到了config/lighthouse.php。
/*
|--------------------------------------------------------------------------
| 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,
],
并且推荐阅读https://webonyx.github.io/graphql-php/security/。
在这个链接中,他们给出了一些示例:
use GraphQL\GraphQL; use GraphQL\Validator\Rules\QueryComplexity; use GraphQL\Validator\DocumentValidator; $rule = new QueryComplexity($maxQueryComplexity = 100); DocumentValidator::addRule($rule); GraphQL::executeQuery(/*...*/);
use GraphQL\GraphQL; use GraphQL\Validator\Rules\QueryDepth; use GraphQL\Validator\DocumentValidator; $rule = new QueryDepth($maxDepth = 10); DocumentValidator::addRule($rule); GraphQL::executeQuery(/*...*/);
但是如何在lighthouse中应用这些呢?
首先,我将这些代码写入了ExampleQuery.php(php artisan lighthouse:query ExampleQuery)。
final class ExampleQuery
{
public function __invoke(_, array $args)
{
$rule = new QueryComplexity(2);
DocumentValidator::addRule($rule);
$rule2 = new QueryDepth(2);
DocumentValidator::addRule($rule2);
return [
...
];
}
}
但是这样无法捕获任何问题。
我认为lighthouse在vendor/nuwave/.../GraphQLController.php中启动,所以我无法执行GraphQL::executeQuery(/*...*/);
@complexity指令也不起作用,@complexity(resolver: "App\\Security\\ComplexityAnalyzer@userPosts")不会调用userPosts函数。
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;
}
}
我错过了什么?请帮助我睡个舒服觉。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
它已经实现了,你只需要设置值。
'security' => [ 'max_query_complexity' => 100, 'max_query_depth' => 10, ],复杂度分数计算可以使用@complexity指令对每个字段进行修改。