Search code examples
graphqlapolloexpress-graphql

graphql role based authorization


I'm new to GraphQL and going to build a solution using GraphQL.

Everything looks cool but just concerned on how to implement the role based authorization inside GraphQL server (I'm considering using GraphQL.js/ apollo server)

I will have a users table which contains all users. Inside the users table there's a roles field which contains the roles of the particular user. The queries and mutations will be granted based on the roles of the user.

How can I implement this structure?

THANKS!


Solution

  • I've recently implemented role based authorisation by using GraphQL Shield, I found that using that package was the simplest way to do it. Otherwise you could add custom schema directives, here's a good article on how to do that: https://dev-blog.apollodata.com/reusable-graphql-schema-directives-131fb3a177d1.

    There are a few steps you need to take to setup GraphQL Shield:

    1 - Write an authentication function, here's a rough example you'll want to be doing much more than this i.e using JWTs and not passing the id:

    export const isAdmin = async ({ id }) => {
      try {
        const exists = await ctx.db.exists.User({
          id: userId,
          role: 'ADMIN',
        });
    
        return exists
      } catch (err) {
        console.log(err);
        return false
      }
    }
    

    2 - In the file where you export all of your mutations and queries add the check:

    const resolvers = {
     ...your queries and mutations
    }
    
    const permissions = {
       Query: {
         myQuery: isAdmin
       }
    }
    
    export default shield(resolvers, permissions);
    

    This will now the isAdmin function every time your Query is requested.

    I hope that helps