Course contentsShow
← Node.js
Lesson 1019 of 1,9809. Authentication and Identity ManagementFree lesson

Securing GraphQL Identity Context

Inject authentication context into resolvers safely in a single-endpoint architecture.

In this lesson, you will learn how to securely pass authenticated user information into your GraphQL resolvers using the context object in a single-endpoint architecture.

The Role of Context

In a GraphQL server, the context object is your primary bridge between the incoming HTTP request and your resolver logic. Because GraphQL operates on a single endpoint (typically /graphql), you cannot rely on traditional middleware patterns to attach user data to specific routes. Instead, you must intercept the incoming request—usually via an Authorization header—verify the user's identity, and attach the resulting user object to the context before execution begins.

Implementation Strategy

To keep this secure, follow the "Verify-then-Inject" pattern. By performing authentication at the server startup phase (via an context factory function), you ensure that every resolver has access to a consistent, pre-validated identity object.

Consider this implementation using apollo-server:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: async ({ req }) => {
    // 1. Extract the token
    const token = req.headers.authorization || '';
    
    // 2. Validate the identity (e.g., verify JWT)
    const user = await verifyUserToken(token);
    
    // 3. Inject into context
    return { user };
  },
});

Why This is Secure

  1. Immutable Context: By injecting the user object during the request lifecycle, you prevent resolvers from accidentally overwriting identity data.
  2. Centralized Logic: Authentication logic lives in one place. If the token validation logic changes, you only update the context factory, not every resolver.
  3. Defense-in-Depth: If the verifyUserToken function fails, you can throw an AuthenticationError. Because this happens inside the context function, the GraphQL execution engine will halt before any sensitive resolver logic (like fetching a private database record) is ever triggered.

Always ensure the user object in your context contains only the minimum necessary information, such as id and roles, rather than the entire database entity, to keep your identity footprint lean and secure.

Key Takeaway: Inject identity context at the server level by validating credentials within the context factory function to ensure every resolver operates on a trusted, authenticated user object.