Authentication: Who Is Making the Request
GraphQL itself has no built-in concept of authentication — unlike REST, where different resources might live behind different endpoints with different auth middleware, a GraphQL API typically exposes a single HTTP endpoint, so authentication happens once, outside the GraphQL execution layer, usually by validating a bearer token (a JWT or opaque session token) in the Authorization header before the request ever reaches the schema. The result of that validation — typically a decoded user ID, roles, and scopes — is placed into the shared context object that every resolver in the request receives, giving every field resolver a consistent, already-verified view of who is asking.
Cricket analogy: Authentication is like checking a broadcaster's press credentials at the stadium's single media entrance before anyone reaches the pitch — once verified, that identity badge is recognized everywhere inside, from the commentary box to the dressing room corridor.
Authorization: Field-Level Access Control
Authorization — deciding what an authenticated identity is allowed to see or do — is where GraphQL differs meaningfully from REST, because a single GraphQL query can touch dozens of fields across many types in one request, so access control has to be enforced at the field-resolver level rather than at the endpoint level. The common pattern is to keep resolvers thin and check permissions inside each resolver (or via a wrapping directive like @auth) against the context.user populated during authentication, returning null for unauthorized nullable fields or throwing a typed GraphQLError with an extension code like FORBIDDEN for non-nullable ones, rather than trying to gate access at the HTTP layer.
Cricket analogy: Field-level authorization is like a stadium granting a credentialed reporter access to the press box and mixed zone, but not the dressing room — the same verified badge grants different access at different specific locations, checked individually at each door.
const resolvers = {
Query: {
salaryReport: (_parent, _args, context) => {
if (!context.user) {
throw new GraphQLError('Not authenticated', {
extensions: { code: 'UNAUTHENTICATED' },
});
}
if (!context.user.roles.includes('HR_ADMIN')) {
throw new GraphQLError('Not authorized', {
extensions: { code: 'FORBIDDEN' },
});
}
return getSalaryReport();
},
},
User: {
email: (user, _args, context) =>
context.user?.id === user.id || context.user?.roles.includes('ADMIN')
? user.email
: null,
},
};Distinguish UNAUTHENTICATED (no valid identity at all — typically a 401-equivalent) from FORBIDDEN (a valid, known identity that simply lacks permission — typically a 403-equivalent) in your error extension codes. Clients often need to react differently — redirecting to login for the former, showing a permission message for the latter — and collapsing both into one generic error code makes that impossible.
Authorization at the Schema vs Resolver Layer
Some teams push authorization even earlier than the resolver body, using schema-level constructs — a custom @auth directive applied declaratively in the SDL, or a schema-visitor pattern that wraps resolvers automatically — so permission requirements are visible right next to the field definition rather than buried inside resolver logic that has to be read to discover what's protected. This tends to scale better across a large schema with many contributors, since a new field's access requirement is self-documenting in the schema itself, though it still ultimately relies on the same context.user populated during authentication and the same underlying checks — the directive is a more discoverable and consistent way to apply them, not a fundamentally different mechanism.
Cricket analogy: Declaring @auth(requires: SELECTOR) right on a field is like printing 'selectors only' directly on a document's cover page instead of burying the restriction in paragraph 12 — anyone glancing at the schema immediately sees the access rule.
A classic GraphQL authorization mistake is checking permissions only at the top-level query field and assuming nested fields are safe by association. If post(id: ID!): Post checks that a user can view a post, but Post.author.email has no independent check, any client can walk the graph — post { author { email } } — to reach data that should have been separately protected. Every sensitive field needs its own authorization check, not just the entry point.
Authorization for Mutations and Subscriptions
Mutations need the same field-level scrutiny as queries but with higher stakes, since a missed check can let an authenticated-but-unauthorized user modify or delete data rather than just view it — production GraphQL APIs commonly pair coarse role checks (@auth(requires: ADMIN)) with finer object-level checks inside the resolver body, like verifying context.user.id === post.authorId before allowing deletePost. Subscriptions add a further wrinkle: authorization typically has to be checked twice — once during the WebSocket connection handshake (via connection_init payload) to establish who's connecting at all, and again inside the subscribe function itself, since a user's permissions might change or a specific subscription argument (like a particular orderId) needs to be checked against that specific user's ownership.
Cricket analogy: Checking authorization twice for a subscription is like verifying a broadcaster's general press pass at the stadium gate, then separately confirming at the commentary box door that this specific pass covers today's particular match, not just any match at the venue.
- GraphQL has no built-in authentication; a bearer token is typically validated once and placed into a shared resolver
context. - Authorization must be enforced at the field-resolver level, since a single query can traverse many types and fields.
- Distinguish UNAUTHENTICATED (no valid identity) from FORBIDDEN (valid identity, insufficient permission) in error extension codes.
- Schema-level directives like @auth make permission requirements discoverable next to the field, but rely on the same underlying context checks.
- Checking authorization only at a top-level query field is a common mistake — every sensitive nested field needs its own check.
- Mutations require both coarse role checks and finer object-ownership checks before allowing modification.
- Subscriptions need authorization both at the connection handshake and again inside the subscribe function for specific arguments.
Practice what you learned
1. Where is authentication typically handled in a GraphQL API?
2. Why must authorization in GraphQL be enforced at the field-resolver level rather than the endpoint level?
3. What is the common authorization mistake described regarding nested fields?
4. Why do subscriptions often require authorization checks in two places?
5. What is the difference between UNAUTHENTICATED and FORBIDDEN error codes?
Was this page helpful?
You May Also Like
Directives in GraphQL
Understand built-in and custom GraphQL directives, how they alter query execution and schema behavior, and where to apply them safely.
Subscriptions Explained
Learn how GraphQL subscriptions deliver real-time updates over a persistent connection, and how to run them reliably in production.
Schema Stitching and Federation
Learn the two main approaches to composing multiple GraphQL services into a single unified graph, and when to choose each.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics