本文介绍了在GraphQL服务器中实现访问控制的好的模式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:

我有一组模型,包括用户和其他各种模型,其中一些模型包含对用户的引用.我将展示这些模型,以便通过 Graffiti 生成的GraphQL API进行查询,该API由Mongo数据库使用 graffiti-mongoose 适配器.我当前的REST API(我正在迁移到GraphQL)使用JSON Web令牌对用户进行身份验证,并在服务器端具有一些自定义权限逻辑来处理访问控制.

I have a set of models, including a User and various other models, some of which contain references to a User. I am exposing these models for querying via a GraphQL API generated by Graffiti, backed by a Mongo database using the graffiti-mongoose adaptor. My current REST API (which I am migrating to GraphQL) uses JSON Web Tokens to authenticate users, and has some custom permission logic on the server side to handle access control.

问题:

我想基于当前登录用户来限制对GraphQL中对象的访问.某些模型应该可以通过未经身份验证的调用进行读取.大多数其他模型应仅由创建它们的用户访问.通过Graffiti生成的API管理对对象的访问控制的最佳方法是什么?

I'd like to restrict access to objects in GraphQL based upon the current logged-in user. Some models should be accessible for reads by unauthenticated calls. Most other models should be only accessible to the User who created them. What's the best way to manage access control to objects via the Graffiti-generated API?

通常,对于GraphQL,是否有良好的访问控制模式?尤其是,有没有使用Graffiti做到这一点的好例子或库?

注释:

我了解钩子前后均已实现实现了涂鸦 -mongoose,并且可以可以用于进行基本的二进制检查以进行身份​​验证.我想看看如何在GraphQL API中使用更详细的访问控制逻辑.将来,我们将希望支持诸如管理员之类的东西,这些人有权访问由某些用户组(例如,其隶属关系包括管理员的用户)创建的模型实例.

I understand that pre- and post- hooks have been implemented for graffiti-mongoose, and that they can be used to do basic binary checks for authentication. I'd like to see how a more detailed access-control logic could be worked into a GraphQL API. In the future, we'll want to support things like Administrators who have access to model instances created by a certain group of Users (e.g. Users whose Affiliations include that of the Administrator).

推荐答案

通常GraphQL不会直接处理访问控制,而是将这种责任委派给与其连接的任何数据系统.在您的情况下,听起来像猫鼬.

Typically GraphQL does not handle access control directly, instead delegating that responsibility to whatever data system it interfaces with. In your case that sounds like Mongoose.

由于访问控制逻辑通常是任意逻辑(例如,该用户是否被禁止使用某些内容?该内容的发布者是否通过自定义隐私设置限制了该内容?等),听起来像是您的这种访问方式控制逻辑实际上是自定义的,它应该存在于解析"函数中,该函数为GraphQL字段生成一个值.

Since access control logic is often arbitrary logic (for example, has this user been banned from some content? did the publisher of that content restrict it with custom privacy settings? etc.), and it sounds like in your case this access control logic is in fact custom, it should live in the "resolve" function which produces a value for a GraphQL field.

例如:

var UserType = new GraphQLObjectType({
  name: 'User',
  fields: {
    name: { type: GraphQLString },
    birthday: {
      type: GraphQLString,
      resolve(user, context) {
        var auth = context.myLoggedInAuth;
        if (myCanAuthSeeBirthday(auth, user)) {
          return user.birthday;
        }
      }
    }
  }
});

这篇关于在GraphQL服务器中实现访问控制的好的模式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 13:29