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

后端 未结 2 1518
清歌不尽
清歌不尽 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;
            }
          }
        }
      }
    });
    
    0 讨论(0)
  • 2021-02-08 18:15

    I create a rule base access control to be used with GraphQL.

    https://github.com/joonhocho/graphql-rule

    It is simple and unopionated that it can be used with or without GraphQL.

    You can use it with a plain javascript objects.

    Hope it helps GraphQLers!

    0 讨论(0)
提交回复
热议问题