Bird
Raised Fist0
GraphQLquery~10 mins

Context-based authentication in GraphQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Context-based authentication
User sends GraphQL request
↓
Extract user context (IP, device, location)
↓
Check context against rules
↓
Allow access
↓
Return response or error
The flow shows how a GraphQL request is checked using user context like IP or device to decide access.
Execution Sample
GraphQL
query getUserData {
  user(id: "123") {
    name
    email
  }
}
A GraphQL query requesting user name and email, which triggers context-based authentication checks.
Execution Table
StepActionContext ExtractedRule Check ResultAccess DecisionResponse
1Receive GraphQL queryN/AN/AN/AWaiting
2Extract context from requestIP=192.168.1.10, Device=MobileN/AN/AWaiting
3Check if IP is trustedIP=192.168.1.10YesAllowProceed
4Check if device is recognizedDevice=MobileYesAllowProceed
5Return user dataN/AN/AAllow{ user: { name: "Alice", email: "alice@example.com" } }
6EndN/AN/AN/ACompleted
💡 Access allowed after context checks pass, user data returned.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
IPN/A192.168.1.10192.168.1.10192.168.1.10192.168.1.10
DeviceN/AMobileMobileMobileMobile
AccessDecisionN/AN/AAllowAllowAllow
ResponseN/AN/AN/AN/A{ user: { name: "Alice", email: "alice@example.com" } }
Key Moments - 2 Insights
Why do we extract context before checking rules?
Context like IP and device must be known first to apply rules correctly, as shown in steps 2 and 3 of the execution_table.
What happens if the IP is not trusted?
If IP check fails (step 3), access would be denied or extra verification requested, stopping the flow before returning data.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the Access Decision at step 3?
AAllow
BDeny
CPending
DError
💡 Hint
Check the 'Access Decision' column at step 3 in the execution_table.
At which step is the user data returned in the response?
AStep 2
BStep 5
CStep 4
DStep 6
💡 Hint
Look at the 'Response' column to find when user data is sent back.
If the device was unrecognized, how would the Access Decision change at step 4?
APending
BAllow
CDeny or request 2FA
DNo change
💡 Hint
Refer to the concept_flow where 'No' branch leads to denial or extra verification.
Concept Snapshot
Context-based authentication in GraphQL:
- Extract user context (IP, device, location) from request
- Check context against security rules
- Allow or deny access based on checks
- Return data only if context is trusted
- Helps secure APIs by adapting to user environment
Full Transcript
Context-based authentication in GraphQL means checking details like IP address and device type when a user sends a query. The system first extracts this context, then compares it to trusted rules. If the context matches trusted values, access is allowed and the requested data is returned. If not, access is denied or extra verification is requested. This process helps keep data safe by making sure only trusted users and devices get access.

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

  1. Step 1: Understand context-based authentication

    It uses information from the request, like tokens, to verify who the user is.
  2. Step 2: Identify the main goal

    The goal is to check user identity to allow or deny access to data.
  3. Final Answer:

    To verify user identity using request information -> Option B
  4. 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

  1. Step 1: Identify how context receives request info

    Context function receives an object with request (req) and response (res).
  2. Step 2: Correctly extract user from request

    User info is usually attached to req, so context: ({ req }) => ({ user: req.user }) is correct.
  3. Final Answer:

    context: ({ req }) => ({ user: req.user }) -> Option A
  4. Quick Check:

    Context uses req.user = context: ({ req }) => ({ user: req.user }) [OK]
Hint: Context function gets req, extract user from req.user [OK]
Common Mistakes:
  • Using res instead of req
  • Passing user as argument instead of req
  • Setting static user instead of dynamic
3. Given this resolver snippet, what will be the output if context.user is { id: 5, role: 'admin' }?
resolve(parent, args, context) {
  if (context.user?.role === 'admin') {
    return 'Access granted';
  } else {
    return 'Access denied';
  }
}
medium
A. 'Access denied'
B. null
C. 'Access granted'
D. Error: Cannot read property 'role' of undefined

Solution

  1. Step 1: Check user role in context

    The code checks if context.user.role equals 'admin'. Given context.user.role is 'admin', condition is true.
  2. Step 2: Determine returned string

    Since condition is true, the resolver returns 'Access granted'.
  3. Final Answer:

    'Access granted' -> Option C
  4. Quick Check:

    context.user.role === 'admin' -> 'Access granted' [OK]
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

  1. Step 1: Check context function parameter

    ApolloServer passes an object with req property, so context should destructure it as ({ req }).
  2. Step 2: Identify correct usage of authorization header

    Authorization header is accessed via req.headers.authorization, so destructuring is needed.
  3. Final Answer:

    The context function should destructure req as ({ req }) -> Option A
  4. 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

  1. Step 1: Understand access rules

    Access is allowed if user owns data (user.id === args.id) or user is admin (role === 'admin').
  2. 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.
  3. Final Answer:

    if (context.user.id === args.id || context.user.role === 'admin') { return 'Allowed'; } else { return 'Denied'; } -> Option D
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard