laravel - Laravel Lighthouse 中的授权
问题描述
在我的 graphql API 中,我必须通过两个不同的因素授权对字段的请求。用户是否被授权访问数据或数据是否属于用户。例如,用户应该能够看到自己的用户数据,并且所有具有管理员权限的用户也应该能够看到这些数据。我想保护字段,因此具有不同权限的用户可以访问某种类型的某些字段,但不能访问所有字段。
我试图用 来做到这一点@can
,但我没有找到任何方法来获取当前访问的模型。我可以得到模型,什么时候@can
在查询或整个类型上使用。
在文档中创建一个指令来保护具有权限的字段也不符合我的需要,因为我在这里没有得到模型。
有没有好办法来处理我的授权需求?
我正在使用 Laravel 7 和 Lighthouse 4.16。
解决方案
我不明白你的问题 100%。有两种情况:
- 您想保护根查询/突变字段。为此,您可以使用 laravel 策略和
@can
指令。像这样的东西:
type Query {
protectedPost(postId: ID! @eq): Post @find @can(ability: "view", find: "id")
}
在你的PostPolicy
:
class PostPolicy
{
//...
public function view(User $user, Post $post)
{
// check if use has access to data
if ($post->author_id === $user->id || $user->role === UserRole::Admin) {
return true;
}
return false;
}
}
也不要忘记将您的策略注册到模型。
- 您想保护您的类型的部分字段。例如,你有一个
Post
类型
type Post {
id: ID!
secretAdminComment: String
}
而你想要保护secretAdminComment
。这似乎有点棘手,但通常您可以使用@can
指令代码并以您需要的方式对其进行扩展。主要逻辑是 - 如果用户能够访问 - 使用常规字段解析器,如果不能 - 返回 null。我会给你一个例子,说明我是如何为我的应用程序实现它的。在我的应用中,用户可能有多个角色。也可以从当前/嵌套字段(或 laravel 中的模型)传递用户 ID 以检查授权用户。
namespace App\GraphQL\Directives;
use App\Enums\UserRole;
use App\User;
use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Exceptions\DefinitionException;
use Nuwave\Lighthouse\Schema\Directives\BaseDirective;
use Nuwave\Lighthouse\Schema\Values\FieldValue;
use Nuwave\Lighthouse\Support\Contracts\DefinedDirective;
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class CanAccessDirective extends BaseDirective implements FieldMiddleware, DefinedDirective
{
public static function definition(): string
{
return /** @lang GraphQL */ <<<'SDL'
"""
Checks if user has at least one of the role, or user ID is match the value of path defined in allowForUserIdIn. If there are no matches, returns null instead of regular value
"""
directive @canAccess(
"""
The user roles to check
"""
roles: [String!]
"""
Custom null value
"""
nullValue: Mixed
"""
Define if user assigment should be checked. Currently authanticated user ID will be compared to defined path relative to root.
"""
allowForUserIdIn: String
) on FIELD_DEFINITION
SDL;
}
/**
* @inheritDoc
*/
public function handleField(FieldValue $fieldValue, Closure $next): FieldValue
{
$originalResolver = $fieldValue->getResolver();
return $next(
$fieldValue->setResolver(
function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($originalResolver) {
$nullValue = $this->directiveArgValue('nullValue', null);
/** @var User $user */
$user = $context->user();
if (!$user) {
return $nullValue;
}
// check role
$allowedRoles = [];
$roles = $this->directiveArgValue('roles', []);
foreach ($roles as $role) {
try {
$allowedRoles[] = UserRole::getValue($role);
} catch (\Exception $e) {
throw new DefinitionException("Defined role '$role' could not be found in UserRole enum! Consider using only defined roles.");
}
}
$allowedViaRole = count(array_intersect($allowedRoles, $user->roles)) > 0;
// check user assignment
$allowForLinkedUser = false;
$allowForUserIdIn = $this->directiveArgValue('allowForUserIdIn');
if ($allowForUserIdIn !== null) {
$compareToUserId = array_reduce(
explode('.', $allowForUserIdIn),
function ($object, $property) {
if ($object === null || !is_object($object) || !(isset($object->$property))) {
return null;
}
return $object->$property;
},
$root
);
$allowForLinkedUser = $user->id === $compareToUserId;
}
if ($allowedViaRole || $allowForLinkedUser) {
return $originalResolver($root, $args, $context, $resolveInfo);
}
return $nullValue;
}
)
);
}
}
这是该指令的用法,该指令为某些角色提供访问权限:
type Post {
id: ID!
secretAdminComment: String @canAccess(roles: ["Admin", "Moderator"])
}
或授予链接到该字段的用户的访问权限。因此,只有 ID 等于的用户$post->author_id
才能获取该值:
type Post {
id: ID!
author_id: ID!
secretAdminComment: String @canAccess(allowForUserIdIn: "author_id")
}
而且您还可以组合这两个参数,因此如果用户具有其中一个角色或具有定义在$post->author_id
.
type Post {
id: ID!
author_id: ID!
secretAdminComment: String @canAccess(roles: ["Admin", "Moderator"], allowForUserIdIn: "author_id")
}
您还可以通过nullValue
参数定义自定义空值。
我希望我能帮助你 =)
推荐阅读
- python - 如何制作可索引的集合数组
- ruby-on-rails - 带有 ActionCable 的 Rails 6 可以实现长轮询 API 吗?
- javascript - 对象值仅附加到一个选择选项并在下一个选项上停止
- jestjs - 如何使用 cls-hooked 非托管事务?
- javascript - 在嵌入式中查看 PDF 中的 XML
- flutter - Flutter,如何使我的图标与我的 DropdownButtonFormField 大小相同?
- wordpress - 尝试从 .twig 文件加载 WP 插件简码
- php - 将 Laravel 翻译变量插入到电子邮件内联样式中
- jakarta-ee - 为什么要创建 JBoss 所有这些事务
- python - Python 上出现多个元素的概率为 50%