Laravel Lighthouse授权

问题描述

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

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

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

解决方法

我不明白您的问题有100%。有两种情况:

  1. 您要保护根查询/突变字段。为此,您可以使用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;
    }
}

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


  1. 您想部分保护您类型的字段。例如。您有一个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中定义的ID,则可以访问。

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

您还可以通过nullValue参数定义自定义的空值。

希望我能帮助您=)

,

您是否尝试为模型实施laravel策略?

https://laravel.com/docs/7.x/authorization#generating-policies

@can应该与模型策略一起使用:)

https://lighthouse-php.com/4.16/api-reference/directives.html#can