Laravel 灯塔中的授权

Authorisation in Laravel Lighthouse

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

我尝试用 @can 来做到这一点,但我没有找到任何方法来获取当前访问的模型。我可以得到模型,什么时候在查询或整个类型上使用 @can
docs 中创建一个指令来保护具有权限的字段也不符合我的需要,因为我在这里没有得到模型。

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

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

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

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

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

我不是 100% 理解你的问题。有两种情况:

  1. 您想保护根 query/mutation 字段。为此,您可以使用 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 指令代码并以您需要的方式扩展它。主要逻辑就像 - 如果用户能够访问 - 使用常规字段解析器,如果不能 - return null。我会给你一个例子,说明我是如何为我的应用程序实现它的。在我的应用程序中,用户可能有多个角色。也可以从 current/nested 字段(或 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 参数定义自定义空值。

希望能帮到你 =)