0
0
GraphQLquery~5 mins

Role-based access control in GraphQL

Choose your learning style9 modes available
Introduction

Role-based access control helps keep data safe by letting only certain people do certain things. It makes sure users see or change only what they are allowed to.

When you want to let managers see all employee records but regular employees see only their own.
When you want to allow admins to add or delete data but users can only read it.
When you want to hide sensitive information from some users based on their job role.
When you want to control who can update or delete posts in a blog app.
When you want to give different access levels in a school system for students, teachers, and staff.
Syntax
GraphQL
directive @hasRole(roles: [String!]) on FIELD_DEFINITION

type Query {
  getData: [Data] @hasRole(roles: ["admin", "manager"])
}
The @hasRole directive checks if the user has one of the allowed roles before running the query.
Roles are listed as strings inside the roles array.
Examples
This query lets only admins fetch all users.
GraphQL
type Query {
  allUsers: [User] @hasRole(roles: ["admin"])
}
This mutation allows admins and editors to delete posts.
GraphQL
type Mutation {
  deletePost(id: ID!): Post @hasRole(roles: ["admin", "editor"])
}
This query lets regular users and admins see their profile.
GraphQL
type Query {
  myProfile: User @hasRole(roles: ["user", "admin"])
}
Sample Program

This example shows a query that only admins can run to get secret data.

GraphQL
directive @hasRole(roles: [String!]) on FIELD_DEFINITION

type Query {
  secretData: String @hasRole(roles: ["admin"])
}

# Example resolver logic (not GraphQL schema):
# If user role is 'admin', return 'Top secret info'. Otherwise, deny access.
OutputSuccess
Important Notes

Role-based access control is often done using directives or middleware in GraphQL.

Always check user roles on the server side to keep data safe.

Summary

Role-based access control limits data access based on user roles.

Use directives like @hasRole to protect queries and mutations.

This helps keep your app secure and organized.