GraphQL Auth: Identity in the Context, Authorization in the Domain Logic
The GraphQL context carries the identity of a request. Whether that identity may perform an operation is decided by a central policy in the domain logic.
A resolver that only checks whether a token is present grants every logged-in user access to everything the schema offers. That isn’t a minor flaw in the auth, that is an open backend with a login form in front of it.
The cause is almost always in the same place: this one check holds two questions that deal with entirely different things – and in the code, they have been fused into one. “We check that in the resolver” is therefore an answer that leaves everything open: is it checking whether someone is logged in, or whether they may see this field? As long as that isn’t answered, nobody knows what the application is actually protected against.
Two questions, not one#
Authentication answers the question: Who are you? A token becomes an identity – a user. Authorization answers an entirely different question: What are you allowed to do? Whether this specific user may call this specific field or this specific mutation.
These are different responsibilities, and they even have different failure modes. If you send no token or an invalid one, you get a 401 – not authenticated. If you have a valid token but the wrong role, you get a 403 – authenticated but not authorized. In code reviews, I regularly see the two mixed up, and then both end up at the client as HTTP 500 because an error wasn’t caught. That isn’t a cosmetic problem – a client can react sensibly to 401 and 403 (login flow vs. “no access”), but not to 500.
Once this separation is in place, the real architecture question comes up: where does the identity belong, and how does it reach every resolver that needs it?
Why the context is the right place#
In GraphQL, a contextValue is built per request – an object that is passed to every resolver of the same request. That isn’t an incidental detail; it is the ideal hook for auth.
The reason is the lifetime. The context is created anew once per request and lives exactly as long as that request. No state leaks between two requests, no cleanup is necessary, and I am guaranteed a freshly determined identity for every request. That is exactly where the user belongs.
In Apollo Server 4 – the current major version – this is an async function that you pass in when starting the server. Important: in Apollo Server 4, the context function moves out of the new ApolloServer({...}) constructor to startStandaloneServer or expressMiddleware. If you still have older examples from AS2/AS3 in mind, where context sat directly in the constructor: conceptually identical, it just gets hooked in somewhere else today.
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, {
context: async ({ req }) => {
const raw = req.headers.authorization || '';
const token = raw.replace('Bearer ', '');
const user = await getUserFromToken(token);
return { user };
},
});
Two details that regularly trip someone up in projects. First: in Express, req.headers.authorization is always lowercase – HTTP header keys end up there in lowercase, no matter how the client sends them. Second: an empty header must never pass as “logged in.” The || '' fallback yields an empty string, getUserFromToken('') then cleanly returns null – and null means “unknown,” not “admin.”
With that, the flow looks the same for every request:
flowchart LR C[Client] -- "Authorization:<br/>Bearer token" --> S[GraphQL server] S --> CTX["context()<br/>token to user"] CTX --> R[Resolver] R --> BL[Business logic<br/>checks user + role] BL -- allowed --> DATA[Data] BL -- denied --> ERR["GraphQLError<br/>403 FORBIDDEN"]
You can see it clearly here: authentication happens exactly once, right at the front in context(). From then on, the request carries an identity with it, and everything else is authorization.
What belongs in the context – and what doesn’t#
Because the context is so temptingly practical, it easily turns into a junk room. It pays to keep its contents deliberately short. What belongs in it:
- the identity –
userorviewer, determined from the token - this user’s permissions –
rolesorscopes - request-bound infrastructure – DataLoader instances, so that batching and deduplication work per request
- access to the data layer – a
dbhandle or repositories - request-specific values such as the locale or an auth token to pass on to downstream services
And just as clearly, what does not belong in it:
- global state that lives across requests
- cross-request caches (that is exactly why a DataLoader is per request, not global)
- plaintext secrets that have no business being there
The rule of thumb behind it: anything that applies to exactly this one request and may disappear afterward is in good hands in the context. Anything long-lived belongs elsewhere. If you put DataLoader instances in the context per request, you already know the pattern from the world of efficient data access, by the way – I described it in more detail in connection with lists and cursors in GraphQL pagination.
Authorization in the resolver#
Now the user is in the context, and every resolver can read it – as the third argument, (parent, args, contextValue, info). That is the simplest, most direct form of authorization.
import { GraphQLError } from 'graphql';
const resolvers = {
Query: {
me: (parent, args, { user }) => {
if (!user) {
throw new GraphQLError('Not authenticated', {
extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },
});
}
return user;
},
adminReport: (parent, args, { user }) => {
if (!user?.roles.includes('ADMIN')) {
throw new GraphQLError('Forbidden', {
extensions: { code: 'FORBIDDEN', http: { status: 403 } },
});
}
return buildAdminReport();
},
},
};
Important for anyone still working with older Apollo examples: the former classes AuthenticationError and ForbiddenError from the old apollo-server package no longer exist in Apollo Server 4. The way to go today is GraphQLError from graphql with an extensions.code – UNAUTHENTICATED for the missing login, FORBIDDEN for the missing permission – and optionally the matching HTTP status.
You can already see the separation in the two resolvers: me only checks whether anyone is there at all (authentication enforced), adminReport checks what this someone is allowed to do (authorization). Two questions, two error codes.
Field level versus query level#
Authorization isn’t just a matter of “whole query allowed or not.” GraphQL allows checks at the field level, and that is one of its stronger properties.
Because every field has its own resolver and the check takes effect while the request is being executed, partial responses are possible: the client queries ten fields, the server delivers seven, and for three it gets an error and null – in a single response. That is exactly the behavior you want. A user should see their own name but not the internal credit rating field that only admins are entitled to.
In the grounding repo, a declarative approach shows up for this: an @auth directive with a role enum.
enum Role {
ADMIN
OWNER
USER
}
directive @auth(requires: Role!) on FIELD_DEFINITION
type User {
id: ID!
name: String!
role: String @auth(requires: ADMIN)
}
type Query {
me: User @auth(requires: USER)
}
Here you can see both levels: me @auth(requires: USER) protects an entire query field, role @auth(requires: ADMIN) protects a single field within the type. The directive itself is only a declaration – someone also has to enforce it at runtime. In the current generation of graphql-tools, you do that with a schema transformer.
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';
import { defaultFieldResolver, GraphQLError } from 'graphql';
function authDirectiveTransformer(schema) {
return mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
const directive = getDirective(schema, fieldConfig, 'auth')?.[0];
if (!directive) return fieldConfig;
const { requires } = directive;
const { resolve = defaultFieldResolver } = fieldConfig;
fieldConfig.resolve = (source, args, context, info) => {
if (!context.user) {
throw new GraphQLError('Not authenticated', {
extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },
});
}
if (!context.user.roles.includes(requires)) {
throw new GraphQLError('Forbidden', {
extensions: { code: 'FORBIDDEN', http: { status: 403 } },
});
}
return resolve(source, args, context, info);
};
return fieldConfig;
},
});
}
A note for anyone who comes across older tutorials: the former SchemaDirectiveVisitor is long gone – it hasn’t existed since graphql-tools v6. The approach via mapSchema and getDirective is the current one. If you google SchemaDirectiveVisitor and copy it, you will wonder why nothing can be imported.
As elegant as the directive looks: it is only half the truth. And this is exactly where the interesting discussions in the team begin.
Why auth doesn’t belong in the schema#
The @auth directive feels like the perfect solution at first – permissions sit right on the field, declarative, readable. For prototypes and for learning, that is perfectly fine. But as the sole strategy, it leads into a dead end, and the official GraphQL docs are surprisingly clear about it: authorization belongs in the business logic layer, not in the schema.
The reason is duplication. Let’s take a typical rule: OWNER – a user may only edit their own posts. This rule can hardly be expressed purely declaratively, because it depends on the concrete data: does this post belong to this user? A directive knows the role but not the relationship between the user and the resource.
And even simple role checks drift apart as soon as the same logic is needed in several places. If the same “may read the post” decision hangs on three fields and at some point is also needed by a REST endpoint or a background job, then you have the rule three or four times – and it drifts apart. That is the core of the argument: a single source of truth instead of scattered copies.
So the clean variant is this: the resolver doesn’t decide on its own; it delegates to a business logic function that receives the context and makes the decision.
const resolvers = {
Query: {
posts: (parent, args, context) => postRepository.getPosts(context),
},
Mutation: {
updatePost: (parent, { id, input }, context) =>
postRepository.updatePost(id, input, context),
},
};
// Business logic layer – authorization lives here
const postRepository = {
async getPosts(context) {
if (!context.user) {
throw new GraphQLError('Not authenticated', {
extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },
});
}
// Owner rule: only the user's own posts
return db.posts.findMany({ where: { authorId: context.user.id } });
},
};
The resolver stays thin and dumb – it takes args and context and passes them on. The actual decision, including the data-dependent OWNER rule, lives in a single place. If another entry point is added tomorrow, it calls the same function. No duplication, no drift.
I like to picture this as three layers, with the schema deliberately in the middle and without any decision-making power:
flowchart TB
subgraph Transport["Transport layer"]
A["Authentication<br/>token to user in the context"]
end
subgraph Schema["Schema layer"]
B["Declarative only<br/>optional @auth as a hint"]
end
subgraph Domain["Business logic layer"]
D["Authorization<br/>may user access this resource?"]
end
Transport --> Schema --> DomainThe message of this picture: identity is determined at the top, the permission decision is made at the bottom. The schema in the middle only describes; it doesn’t decide.
The pitfall that gets most expensive#
There is one mistake I see again and again, and it really hurts: enforcing authorization in the client. The UI hides the “Delete” button if the user isn’t an admin – and everyone is happy. Except that the resolver behind it checks nothing at all.
That isn’t security, that is cosmetics. Anyone who opens the developer tools or sends a GraphQL mutation directly bypasses this “check” in seconds. Hidden buttons are a matter of user guidance, not security. Enforcement must happen on the server – in the resolver or in the business logic layer behind it. The client is welcome to hide buttons as well, so that the UI stays tidy. But the only thing you can rely on is the server.
That also answers the opening question. “We check that in the resolver” isn’t enough as an architecture decision. The identity goes into the context once per request. For the specific operation, the resolver calls a central policy or domain function; that is where the data-dependent permission decision is made. Directives and hidden buttons can make this visible, but they don’t replace this check.
In the projects where auth ended up running quietly, it was never a schema question but a question of lifecycles and responsibilities. The context knows who you are. The business logic knows what you are allowed to do. If the two stay separate, the rest becomes simple.
Further reading#
- Grounding repository MikeBild/introduction-graphql –
introduction-graphql/auth.mdandrecipes/auth/ - graphql.org – Authorization – why authorization belongs in the business logic layer
- Apollo Server – Authentication and authorization – GraphQLError codes,
UNAUTHENTICATEDvs.FORBIDDEN - Apollo Server – The context object – context and contextValue, once per request
Revised and translated from German with the help of AI.