Laravel Lighthouse授权

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-