Laravel Lighthouse中的授权 [英] Authorisation in Laravel Lighthouse

查看:57
本文介绍了Laravel Lighthouse中的授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的graphql API中,我必须通过两个不同的因素来授权对字段的请求.用户是否有权访问数据或数据是否属于用户.例如,用户应该能够看到其自己的用户数据,并且所有具有管理员权限的用户也应该能够看到该数据.我想保护字段,以便具有不同权限的用户可以访问某些类型的字段,但不能访问所有字段.

In my graphql API I have to authorize requests to fields by two different factors. Whether the user is authorized to access the data or whether the data belongs to the user. For example, the user should be able to see its own user data and all users with admin rights should be able to see this data too. I want to protect the fields, so users with different permisions can access some fields of a type, but don't have access all fields.

我尝试使用 @can 进行此操作,但是我没有找到任何方法来获取当前访问的模型.当在查询或整个Type上使用 @can 时,我就可以得到模型.
按照 docs 创建指令以保护字段具有权限的功能也不符合我的需求,因为我在这里没有找到模型.

I tried to do this with @can, but I didn't find any way to get the model that is currently accessed. I can just get the model, when is use @can on a Query or the whole Type.
Creating a directive as in the docs to protect fields with permissions also doesn't fit my needs, as I don't get the model here.

有什么好方法可以处理我的授权需求?
我正在使用Laravel 7和Lighthouse 4.16.

Is there a good way to deal with my authorisation needs?
I'm using Laravel 7 and Lighthouse 4.16.

推荐答案

对于100%的问题我不理解.有两种情况:

I don't understand your issue for 100%. There are two situations:

  1. 您要保护根查询/突变字段.为此,您可以使用laravel策略和 @can 指令.像这样:
  1. You want to protect a root query/mutation field. For this you can use laravel policy and @can directive. Something like this:

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;
    }
}

也不要忘记为模型注册策略.

Also don't forget to register you policy to the model.

  1. 您想部分保护您类型的字段.例如.您有一个 Post 类型,例如

type Post {
    id: ID!
    secretAdminComment: String
}

,并且您要保护 secretAdminComment .这似乎有些棘手,但是通常您可以使用 @can 指令代码并根据需要扩展它.主要逻辑类似于-如果用户能够访问-使用常规字段解析器,否则-返回null.我将为您提供一个示例,说明如何为我的应用程序实现它.在我的应用程序中,用户可能具有多个角色.也可以从当前/嵌套字段(或以laravel表示的模型)传递用户ID来检查授权用户.

and you want to protect secretAdminComment. This seems to be a little tricky, but in general you can use @can directive code and extend it in way you need it. The main logic is like - if user is able to access - use regular field resolver, and if not - return null. I'll give you an example of how I implemented it for my app. In my app users may have multiple roles. Also it is possible to pass a user ID from current/nested field (or model in terms of laravel) to check against an authorized user.


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;
                }
            )
        );
    }
}

这是该指令为某些角色提供访问权限的用法:

And here is the usage of that directive giving access for certain roles:

type Post {
    id: ID!
    secretAdminComment: String @canAccess(roles: ["Admin", "Moderator"])
}

或授予链接到该字段的用户访问权限.因此,只有ID等于 $ post-> author_id 的用户才能获取该值:

Or giving access to user linked to the field. So only user with ID equals to $post->author_id will be able to get the value:

type Post {
    id: ID!
    author_id: ID!
    secretAdminComment: String @canAccess(allowForUserIdIn: "author_id")
}

您还可以结合使用这两个参数,因此,如果用户具有角色之一或具有 $ post-> author_id 中定义的ID,则可以访问该用户.

And you are also able to combine both parameters, so user gets access if he either has one of the roles, or has the ID that is defined in $post->author_id.

type Post {
    id: ID!
    author_id: ID!
    secretAdminComment: String @canAccess(roles: ["Admin", "Moderator"], allowForUserIdIn: "author_id")
}

您还可以通过 nullValue 参数定义自定义null值.

You are also able to define custom null value via nullValue parameter.

希望我能帮助您=)

这篇关于Laravel Lighthouse中的授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆