The guard at the Bookshop warehouse door checks your staff card once, as you walk in. Inside, the stock shelves may only be opened by staff, and that rule is checked every time someone touches a shelf. The card says who you are, the rule on each shelf says what you may do.
Auth on a GraphQL server is the same two questions. Authentication: who are you? That's the guard at the door. Authorization: what may you do? That's the rule on each shelf.
Two questions, two places
The GraphQL specification says nothing about auth at all. That's the server's job, and it's usually split like this:
| Question | Where | When it fails | |
|---|---|---|---|
| Authentication | Who are you? | Once per request, at the HTTP layer, the result put in context |
a fake token: the request is refused, status 401 |
| Authorization | What may you do? | In the resolver, or in the business layer under it | that field is null, with the code UNAUTHENTICATED or FORBIDDEN |
context is every resolver's third argument. The server builds it once per request, so every resolver in one request reads the same user.
Authentication: a token in the header, a user in context
The client sends the token in an HTTP header, not inside the query: Authorization: Bearer token-budi. With fetch, that header goes in headers, beside Content-Type. The server reads it in the context function. In Apollo Server 5:
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import { GraphQLError } from "graphql";
const server = new ApolloServer({ typeDefs, resolvers });
await startStandaloneServer(server, {
// Runs once per request, before any resolver.
context: async ({ req }) => {
const token = req.headers.authorization?.replace("Bearer ", "") ?? "";
if (token === "") return { user: null }; // a guest: the catalog may still be read
const user = await findUserByToken(token);
if (!user) {
throw new GraphQLError("Invalid token", {
extensions: { code: "UNAUTHENTICATED", http: { status: 401 } },
});
}
return { user };
},
});
req.headers.authorizationholds"Bearer token-budi". The wordBeareris dropped, the rest is the token.- With no token,
userisnull. Public fields like a book's title still work. - A token nobody knows refuses the whole request with status 401, before a single resolver runs.
http: { status: 401 }is how Apollo Server picks the HTTP status from an error. - This function builds a new object for every request. Don't keep the user in a global variable, or someone else's request uses it too.
For this lesson, the Bookshop has two accounts, and a new viewer field returns the user who is logged in:
type Query {
# ...the old fields stay
viewer: User
}
type User {
id: ID!
name: String!
role: Role!
}
enum Role {
CUSTOMER
STAFF
}
Authorization header |
context.user |
Response to { viewer { name role } } |
|---|---|---|
| (none) | null |
{ "data": { "viewer": null } } |
Bearer token-budi |
Budi, CUSTOMER |
{ "data": { "viewer": { "name": "Budi", "role": "CUSTOMER" } } } |
Bearer token-sari |
Sari, STAFF |
{ "data": { "viewer": { "name": "Sari", "role": "STAFF" } } } |
Bearer token-fake |
refused | status 401, only errors with the code UNAUTHENTICATED |
Authorization: one rule in the resolvers
The rule: the stock and every mutation are for STAFF only. Write the rule once, then call it in every resolver that needs it:
import { GraphQLError } from "graphql";
// One rule, used by every resolver that needs it.
const authorize = (user) => {
if (!user) throw new GraphQLError("Login required", { extensions: { code: "UNAUTHENTICATED" } });
if (user.role !== "STAFF") throw new GraphQLError("Staff only", { extensions: { code: "FORBIDDEN" } });
};
const resolvers = {
Query: {
viewer: (_, __, context) => context.user,
},
Mutation: {
updateStock: (_, { id, stock }, context) => {
authorize(context.user); // fails here: the stock doesn't change
// ...then change the stock as in the "Mutations" lesson
},
},
Book: {
stock: (book, _, context) => {
authorize(context.user);
return book.stock;
},
},
};
context.usercomes from thecontextfunction above. Resolvers don't read the header themselves.UNAUTHENTICATEDmeans not logged in.FORBIDDENmeans logged in, but not allowed. Both codes are examples from Apollo Server's documentation, as in the "Error Handling" lesson.Book.stockis a field-level rule: anyone may readtitle, only staff may readstock.
Field rules and null
Budi logs in as a customer and sends { books { title stock } }. Only staff may read the stock, and the schema says stock: Int!. Before you look at the response, guess: does Budi still get the book titles?
{
"errors": [
{
"message": "Staff only",
"locations": [{ "line": 4, "column": 5 }],
"path": ["books", 0, "stock"],
"extensions": { "code": "FORBIDDEN" }
}
],
"data": null
}
Budi gets nothing, not even the titles. stock is refused and becomes null, but Int! may not be null. The null climbs to the first book, then to the [Book!]! list, then to data. One rule wipes out the whole response.
A field that may be refused should be nullable. For this lesson the Bookshop's Book.stock becomes stock: Int. The same request from Budi now gives:
{
"data": {
"books": [
{ "title": "The Rainbow Troops", "stock": null },
{ "title": "This Earth of Mankind", "stock": null },
{ "title": "Beauty Is a Wound", "stock": null }
]
}
}
plus three FORBIDDEN errors in errors, with the paths ["books", 0, "stock"], ["books", 1, "stock"] and ["books", 2, "stock"]. The titles arrive, the stock is refused one book at a time. Sari, with a staff token, gets the stock 12, 0 and 5 with no errors.
Keep the rule in one place
The status field is computed from the stock: SOLD_OUT when the stock is 0. A guest asking for { books { title status } } still learns that This Earth of Mankind is sold out, even though stock is refused. Whether that's allowed is a business decision: maybe the shop wants buyers to know. But if the rule is "the stock is secret", a rule that lives only in the Book.stock resolver leaks easily through another field.
That's why graphql.org's documentation recommends putting authorization rules in the business layer: one function, like authorize above, called by every path that touches that data. GraphQL resolvers, an old REST endpoint and background jobs all use the same rule.
The @auth directive: a pattern, not built in
GraphQL has only a few built-in directives, such as @include, @skip and @deprecated. @auth isn't one of them. You can make one yourself so the rule can be read in the schema:
directive @auth on FIELD_DEFINITION
type Book {
# ...the other fields
stock: Int @auth
}
The directive is only a mark. What runs it is code that wraps the resolver of every marked field, for example with @graphql-tools/utils:
import { mapSchema, getDirective, MapperKind } from "@graphql-tools/utils";
import { defaultFieldResolver } from "graphql";
const withAuth = (schema) =>
mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
if (!getDirective(schema, fieldConfig, "auth")?.[0]) return fieldConfig;
const { resolve = defaultFieldResolver } = fieldConfig;
return {
...fieldConfig,
resolve: (source, args, context, info) => {
authorize(context.user); // the same rule
return resolve(source, args, context, info);
},
};
},
});
getDirective looks for @auth on each field, then a marked field's resolver is wrapped: authorize first, then the original resolver. Old examples with SchemaDirectiveVisitor have been removed since graphql-tools version 8.
The same idea also works through middleware that wraps resolvers, for example the graphql-shield library. Either way, it comes down to one rule that runs before that field's resolver. The Lab on this page calls authorize straight in the resolver, because its mini GraphQL engine doesn't run directives in the schema yet.
📌 Introspection and queries that go too deep
- Introspection is the
__schemaquery that returns the whole schema. Apollo Server turns it off by default whenNODE_ENVisproduction. Hiding the schema doesn't replace authorization: an attacker can still guess field names, so every secret field still needs its rule. Public APIs like GitHub's leave it on on purpose. - Queries that go too deep, like
book { author { books { author { books { title } } } } }, can make the server do many times the work, even from a legitimate user. Depth limits and cost (complexity) limits are covered in the "Performance & Caching" lesson.
⚠️ Auth rules that leak or go too far
- The user kept in a global variable. Other requests use it too. Put it in
context, which is built anew for every request. - A secret field with a non-null type. One
FORBIDDENwipes out all ofdata. Make it nullable. - Relying on the client to hide a field. Anyone can send any query straight to the server. The rule must live on the server.
- The rule in only one resolver. A derived field like
status, or a forgotten mutation, opens another way in. One rule function, called from every path.
TL;DR: Authentication (who are you?) runs once per request: the server reads Authorization: Bearer <token> in the context function and puts the user there, null for a guest, and a request with a fake token is refused with status 401. Authorization (what may you do?) runs in the resolvers through one function like authorize, with the code UNAUTHENTICATED (not logged in) or FORBIDDEN (not allowed); at Bookshop, stock and the mutations are for STAFF only. A field that may be refused should be nullable, so the rest of the response still arrives. The rule should live in the business layer so it doesn't leak through another field. @auth is a directive you make yourself that wraps resolvers (with mapSchema, say), not something built into GraphQL. Introspection is usually turned off in production, but that doesn't replace authorization.
⚡ Authentication: once per request, in context
Write:
context: async ({ req }) => {
const token = req.headers.authorization?.replace("Bearer ", "") ?? "";
if (token === "") return { user: null }; // a guest: the catalog may still be read
const user = await findUserByToken(token);
if (!user) {
throw new GraphQLError("Invalid token", {
extensions: { code: "UNAUTHENTICATED", http: { status: 401 } },
});
}
return { user };
},
Meaning: Authentication (who are you?) belongs in the context function, which runs once per request before any resolver. Its result, context.user, is shared with every resolver of that request.
⚡ Authorization: one rule in the resolvers
Write:
const authorize = (user) => {
if (!user) throw new GraphQLError("Login required", { extensions: { code: "UNAUTHENTICATED" } });
if (user.role !== "STAFF") throw new GraphQLError("Staff only", { extensions: { code: "FORBIDDEN" } });
};
Meaning: Authorization (what may you do?) is checked in every resolver that needs it, through one shared rule. No user: UNAUTHENTICATED. Logged in but not staff: FORBIDDEN.
⚡ A field that may be refused should be nullable
Guess first: the schema says stock: Int!, and Budi (not staff) sends { books { title stock } }. Do the titles still arrive?
No. stock is refused and becomes null, but Int! may not be null. The null climbs until the whole data is null, so the titles are gone too.
Meaning: With stock: Int, only stock becomes null and the titles still arrive. Close the other roads that leak the stock too, such as status.