📖 Scenario: You are building a simple GraphQL API for a small online store. The API needs to authenticate users based on a context token to allow access to user-specific data.
🎯 Goal: Build a GraphQL schema and resolver setup that uses context-based authentication to return user data only if the correct token is provided.
📋 What You'll Learn
Create a GraphQL schema with a User type and a Query type with a me field
Add a context object that contains a token string
Implement a resolver for me that checks the token in context and returns user data if the token matches
Return null if the token is missing or invalid
💡 Why This Matters
🌍 Real World
Context-based authentication is used in real APIs to control access to user data based on tokens or session info.
💼 Career
Understanding how to use context in GraphQL for authentication is essential for backend developers building secure APIs.
Progress0 / 4 steps
1
Define the GraphQL schema
Create a GraphQL schema string called typeDefs that defines a User type with fields id (ID!), name (String!), and a Query type with a me field returning User.
GraphQL
Hint
Define the schema as a template string with the required types and fields.
2
Add context with token
Create a variable called context that is an object with a token property set to the string "secret-token-123".
GraphQL
Hint
Create a simple object with the token string.
3
Implement the resolver with token check
Create a resolvers object with a Query field containing a me function. This function takes parent, args, and ctx parameters and returns an object { id: "1", name: "Alice" } only if ctx.token equals "secret-token-123". Otherwise, return null.
GraphQL
Hint
Use a simple if statement inside the resolver to check the token.
4
Complete the GraphQL server setup
Create a variable called server that is an instance of ApolloServer initialized with typeDefs, resolvers, and a context function returning the context object.
GraphQL
Hint
Use new ApolloServer with the correct options.
Practice
(1/5)
1. What is the main purpose of context-based authentication in GraphQL?
easy
A. To cache query results
B. To verify user identity using request information
C. To format the response data
D. To speed up query execution
Solution
Step 1: Understand context-based authentication
It uses information from the request, like tokens, to verify who the user is.
Step 2: Identify the main goal
The goal is to check user identity to allow or deny access to data.
Final Answer:
To verify user identity using request information -> Option B
Quick Check:
Context-based authentication = verify user identity [OK]
Hint: Context holds user info to check identity quickly [OK]
Common Mistakes:
Thinking it speeds up queries
Confusing with data formatting
Assuming it caches results
2. Which of the following is the correct way to add user info to the GraphQL context in a server setup?
easy
A. context: ({ req }) => ({ user: req.user })
B. context: (user) => ({ req: user })
C. context: () => ({ user: 'anonymous' })
D. context: ({ res }) => ({ user: res.user })
Solution
Step 1: Identify how context receives request info
Context function receives an object with request (req) and response (res).
Step 2: Correctly extract user from request
User info is usually attached to req, so context: ({ req }) => ({ user: req.user }) is correct.
Hint: Check user role in context to decide access [OK]
Common Mistakes:
Ignoring optional chaining and assuming error
Confusing role values
Assuming null return
4. Identify the error in this context setup code:
const server = new ApolloServer({
typeDefs,
resolvers,
context: (req) => {
const user = authenticate(req.headers.authorization);
return { user };
}
});
medium
A. The context function should destructure req as ({ req })
B. authenticate function is missing
C. context function should return user directly, not an object
D. Authorization header should be accessed as req.authorization
Solution
Step 1: Check context function parameter
ApolloServer passes an object with req property, so context should destructure it as ({ req }).
Step 2: Identify correct usage of authorization header
Authorization header is accessed via req.headers.authorization, so destructuring is needed.
Final Answer:
The context function should destructure req as ({ req }) -> Option A
Quick Check:
Context param = ({ req }) not (req) [OK]
Hint: Destructure req from context param: ({ req }) [OK]
Common Mistakes:
Using req directly without destructuring
Assuming authenticate is missing error
Returning user instead of object
5. You want to restrict a GraphQL query so only the user who owns the data or an admin can access it. Which context-based authentication check correctly enforces this?
resolve(parent, args, context) {
// args.id is the data owner ID
// context.user has id and role
???
}
hard
A. if (args.id === null) { return 'Allowed'; } else { return 'Denied'; }
B. if (context.user.id !== args.id && context.user.role !== 'admin') { return 'Allowed'; } else { return 'Denied'; }
C. if (context.user.role === 'admin') { return 'Denied'; } else { return 'Allowed'; }
D. if (context.user.id === args.id || context.user.role === 'admin') { return 'Allowed'; } else { return 'Denied'; }
Solution
Step 1: Understand access rules
Access is allowed if user owns data (user.id === args.id) or user is admin (role === 'admin').
Step 2: Check condition logic
if (context.user.id === args.id || context.user.role === 'admin') { return 'Allowed'; } else { return 'Denied'; } correctly uses OR (||) to allow access if either condition is true.
Final Answer:
if (context.user.id === args.id || context.user.role === 'admin') { return 'Allowed'; } else { return 'Denied'; } -> Option D
Quick Check:
Owner or admin -> allow access [OK]
Hint: Use OR to allow owner or admin access [OK]
Common Mistakes:
Using AND instead of OR
Denying admins access
Ignoring user ID check
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.