0
0
GraphQLquery~5 mins

Directive-based authorization in GraphQL

Choose your learning style9 modes available
Introduction

Directive-based authorization helps control who can see or change data in a GraphQL API. It keeps data safe by checking permissions before giving access.

When you want only logged-in users to see certain data.
When some users should only read data but not change it.
When you want to hide sensitive information from some users.
When you want to check user roles before allowing actions.
When you want to keep your API secure without writing extra code everywhere.
Syntax
GraphQL
directive @auth(
  requires: Role = USER
) on OBJECT | FIELD_DEFINITION

enum Role {
  ADMIN
  USER
  GUEST
}
Directives start with @ and add rules to types or fields.
You define roles or permissions inside the directive to check user access.
Examples
This example only lets users with the ADMIN role see secretData.
GraphQL
type Query {
  secretData: String @auth(requires: ADMIN)
}
This example requires users to be logged in (USER role) to access the whole User type.
GraphQL
type User @auth(requires: USER) {
  id: ID!
  email: String
}
This shows how to define the @auth directive and roles for authorization.
GraphQL
directive @auth(requires: Role = USER) on OBJECT | FIELD_DEFINITION

enum Role {
  ADMIN
  USER
  GUEST
}
Sample Program

This GraphQL schema defines a directive @auth to protect fields. publicInfo is open to all. privateInfo needs a USER role. adminInfo needs ADMIN role.

GraphQL
directive @auth(requires: Role = USER) on OBJECT | FIELD_DEFINITION

enum Role {
  ADMIN
  USER
  GUEST
}

type Query {
  publicInfo: String
  privateInfo: String @auth(requires: USER)
  adminInfo: String @auth(requires: ADMIN)
}
OutputSuccess
Important Notes

Directive-based authorization keeps your schema clean and easy to read.

You still need server code to check the user's role when a query runs.

Use roles that match your app's needs for better security.

Summary

Directive-based authorization uses special tags to control access.

You add directives to types or fields to require user roles.

This method helps keep data safe and your API organized.