GraphQL Role-based access control (RBAC) middleware
graphql-rbac provides you a simple way to use Role-based access control in GraphQL. This package integrates with graphql-shield which helps you create a permission layer for your application. Using a schema with array of role, graphql-rbac can help you generate rule functions in graphql-shield. So you can easily use RBAC in your application by providing a schema.
Why graphql-rbac?
- Easy to specify rule permissions for each field in GraphQL.
- Don't need to write rule function by yourself.
Installation
yarn add graphql-rbac
How to use
const roles = 'ADMIN' 'DEVELOPER' const schema = Query: users: 'ADMIN' 'DEVELOPER' Mutation: createUser: 'ADMIN' 'DEVELOPER' updateUser: 'ADMIN' 'DEVELOPER' deleteUser: 'ADMIN' User: password: 'ADMIN' const typeDefs = ` type Query { users: [User!]! } type Mutation { createUser: User! updateUser: User! deleteUser: User } type User { username: String! password: String! }` const resolvers = Query: username: 'Tom' password: '****' username: 'John' password: '****' Mutation: { username: 'Tom' password: '****' } { username: 'John' password: '****' } null const users = admin: role: 'ADMIN' developer: role: 'DEVELOPER' const getUser = async { const auth = reqrequestheadersauthorization let user = {} if usersauth user = usersauth return user} const rbac = roles schema getUser const server = typeDefs resolvers middlewares: rbac user: rbac
Run test
npm run test