What is a good pattern for implementing access control in a GraphQL server?

后端 未结 2 1553
清歌不尽
清歌不尽 2021-02-08 17:51

Background:

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 f

2条回答
  •  轮回少年
    2021-02-08 18:02

    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.

    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.

    For example:

    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;
            }
          }
        }
      }
    });
    

提交回复
热议问题