How to check permissions and other conditions in GraphQL query? How to check permissions and other conditions in GraphQL query? mongoose mongoose

How to check permissions and other conditions in GraphQL query?


You can check a user's permission in the resolve function or in the model layer. Here are the steps you have to take:

  1. Authenticate the user before executing the query. This is up to your server and usually happens outside of graphql, for example by looking at the cookie that was sent along with the request. See this Medium post for more details on how to do this using Passport.js.
  2. Add the authenticated user object or user id to the context. In express-graphql you can do it via the context argument:

    app.use('/graphql', (req, res) => {  graphqlHTTP({ schema: Schema, context: { user: req.user } })(req, res);}
  3. Use the context inside the resolve function like this:

    resolve(parent, args, context){  if(!context.user.isAdmin){    args.isPublic = true;  }  return PostModel.find(args).exec();}

You can do authorization checks directly in resolve functions, but if you have a model layer, I strongly recommend implementing it there by passing the user object to the model layer. That way your code will be more modular, easier to reuse and you don't have to worry about forgetting some checks in a resolver somewhere.

For more background on authorization, check out this post (also written by myself):Auth in GraphQL - part 2


One approach that has helped us solve authorization at our company is to think about resolvers as a composition of middleware. The above example is great but it will become unruly at scale especially as your authorization mechanisms get more advanced.

An example of a resolver as a composition of middleware might look something like this:

type ResolverMiddlewareFn =   (fn: GraphQLFieldResolver) => GraphQLFieldResolver;

A ResolverMiddlewareFn is a function that takes a GraphQLFieldResolver and and returns a GraphQLFieldResolver.

To compose our resolver middleware functions we will use (you guessed it) the compose function! Here is an example of compose implemented in javascript, but you can also find compose functions in ramda and other functional libraries. Compose lets us combine simple functions to make more complicated functions.

Going back to the GraphQL permissions problem lets look at a simple example.Say that we want to log the resolver, authorize the user, and then run the meat and potatoes. Compose lets us combine these three pieces such that we can easily test and re-use them across our application.

const traceResolve =  (fn: GraphQLFieldResolver) =>  async (obj: any, args: any, context: any, info: any) => {    const start = new Date().getTime();    const result = await fn(obj, args, context, info);    const end = new Date().getTime();    console.log(`Resolver took ${end - start} ms`);    return result;  };const isAdminAuthorized =  (fn: GraphQLFieldResolver) =>  async (obj: any, args: any, context: any, info: any) => {    if (!context.user.isAdmin) {      throw new Error('User lacks admin authorization.');    }    return await fn(obj, args, context, info);  }const getPost = (obj: any, args: any, context: any, info: any) => {  return PostModel.find(args).exec();}const getUser = (obj: any, args: any, context: any, info: any) => {  return UserModel.find(args).exec();}// You can then define field resolve functions like this:postResolver: compose(traceResolve, isAdminAuthorized)(getPost)// And then others like this:userResolver: compose(traceResolve, isAdminAuthorized)(getUser)