laravel - Laravel Lighthouse 中的授权

标签 laravel graphql laravel-lighthouse

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

我尝试用@can 来做到这一点,但我没有找到任何方法来获取当前访问的模型。我可以得到模型,什么时候在查询或整个类型上使用 @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 - Laravel Lighthouse 中的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63359841/

相关文章:

GraphQL:利用内省(introspection)功能进行数据突变

laravel-lighthouse - 如何在 Laravel Lighthouse 中的同一突变上插入多个数据?

php - 在 laravel 分页中添加一些数据

php - Laravel 检查缓存标签是否存在

graphql - 是否可以使用graphql多次查询同一字段

php - 通过 user_id 获取 Lighthouse GraphQL 数据所有权

php - Laravel Lighthouse 配置 - 无法找到可发布的资源

laravel 需要使用 carbon 类只显示日期而不是时间

路由中 'uses' 的 Laravel 8 数组可调用语法不起作用

interface - 接口(interface)中包含的 Graphql 类型未添加到 graphene-django 中的模式