0
0
GraphQLquery~30 mins

Directive-based authorization in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Directive-based Authorization in GraphQL
📖 Scenario: You are building a GraphQL API for a simple blog platform. You want to control access to certain fields and operations based on user roles using directive-based authorization.
🎯 Goal: Create a GraphQL schema that uses a custom @auth directive to restrict access to fields and queries based on user roles.
📋 What You'll Learn
Define a custom directive called @auth that accepts a role argument.
Create a User type with fields id, username, and email.
Create a Query type with a field users that returns a list of User.
Apply the @auth(role: "ADMIN") directive to the users query to restrict it to admin users.
Apply the @auth(role: "USER") directive to the email field to restrict email visibility to users with the USER role.
💡 Why This Matters
🌍 Real World
Directive-based authorization is commonly used in GraphQL APIs to control access to data based on user roles or permissions.
💼 Career
Understanding how to implement and use custom directives for authorization is valuable for backend developers working with GraphQL APIs.
Progress0 / 4 steps
1
Define the @auth directive and User type
Create a GraphQL schema that defines a directive called @auth which takes a role argument of type String!. Also, define a User type with fields id of type ID!, username of type String!, and email of type String!.
GraphQL
Hint

Use the directive keyword to define @auth with a role argument. Then define the User type with the specified fields.

2
Add the Query type with users field
Add a Query type to the schema with a field called users that returns a list of User (use [User!]! as the return type).
GraphQL
Hint

Define the Query type and add the users field returning a non-null list of non-null User objects.

3
Apply @auth(role: "ADMIN") directive to users query
Modify the users field in the Query type to include the @auth(role: "ADMIN") directive to restrict access to admin users only.
GraphQL
Hint

Add the @auth(role: "ADMIN") directive right after the users field type declaration.

4
Apply @auth(role: "USER") directive to email field
Modify the email field in the User type to include the @auth(role: "USER") directive to restrict email visibility to users with the USER role.
GraphQL
Hint

Add the @auth(role: "USER") directive immediately after the email field type.