Authentication and authorization

Intermediate · 23 min

Authenticate once per request in the context function, then authorize where data is resolved, with stable error codes and no top-level-only checks.

Before thisContext and resolver argumentsErrors and partial responses

Apollo GraphQL · 23 min

Authentication and authorization

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Apollo GraphQLReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Authentication answers who is calling and happens once per HTTP request, in the context function, before any resolver runs.
  • Authorization answers what this caller may see or do and has to be enforced where data is resolved, because one query can reach the same object through many paths.
  • Putting authorization only at the endpoint or in the top-level query field leaves every nested path unprotected.
  • Put the rules in one place, a service or data layer your resolvers call, so the schema is not the only line of defence.
  • Use stable error codes in extensions, such as UNAUTHENTICATED and FORBIDDEN, so clients can react without parsing messages.

Two questions, asked at different places

Authentication asks who is calling. Authorization asks what that caller may do. GraphQL does not define either. The spec has no concept of a user, a token or a permission, which means the pattern is yours to build, and a mistake does not fail loudly; it returns data to someone who should not see it.

The two questions land in different places in a GraphQL server because of how requests arrive. There is a single endpoint, so you cannot protect /admin by URL. Authentication belongs at the edge of the request. Authorization has to follow the data.

Authenticate in the context

You met the context as the object every resolver receives. It is built once per request, which makes it the natural home for the caller’s identity. Read the header, verify the token, look up the user, put the result on the context:

const yoga = createYoga({
  schema,
  context: ({ request }) => {
    const token = (request.headers.get("authorization") ?? "").replace("Bearer ", "");
    return { user: verify(token) }; // null when missing or invalid
  },
});

I wrote and ran this shape with Yoga 6.1.0 and node:test, using a lookup table in place of real JWT verification. In real code verify checks a signature and expiry; see JWTs, API keys and sessions for the token side and authorization models for roles and attributes.

A deliberate choice: the context function does not reject anonymous requests. It records that the caller is anonymous, and resolvers decide. Public fields such as a product catalogue should still work without a token. If you throw in the context function, every request without a token fails, including the ones that should succeed.

Authorize where data is resolved

Here is the test I ran. The schema had me for any signed-in user and secret for admins only:

me: (_, __, { user }) => {
  if (!user) throw new GraphQLError("Not authenticated", { extensions: { code: "UNAUTHENTICATED" } });
  return user.id;
},
secret: (_, __, { user }) => {
  if (user?.role !== "admin") throw new GraphQLError("Forbidden", { extensions: { code: "FORBIDDEN" } });
  return "s3";
},

Three tests passed: an anonymous call to me came back with code UNAUTHENTICATED and data: null (the field is non-null, so the error propagates to the root, as explained in nullability in practice); a plain user could read me and got FORBIDDEN for secret; an admin could read secret.

The extensions.code matters. Clients should switch on a code, not on message text. Note also that GraphQL answers HTTP 200 for these, as seen in calling GraphQL with fetch, so a gateway that expects a 401 will not see one unless you map it yourself.

Why the top-level check is not enough

Suppose only Query.adminReport checks the role. A client who cannot call it can still write { me { team { reports { ... } } } } if some other path reaches the same objects. GraphQL is a graph; objects are reachable along many edges. Authorization that guards a root field guards one door in a building with many.

That is why permission checks belong with the data. Three layers help:

  1. Resolver checks for coarse questions: signed in, right role.
  2. Object or field checks for ownership: a Book.privateNotes resolver confirms the caller owns the book before returning anything.
  3. A data layer that takes the user and refuses to return what they cannot see, so a resolver that forgets a check still cannot leak. Hand ctx.user to a service such as bookService.forUser(ctx.user) and let it apply the rules once.

Directives (@auth(role: ADMIN)) and libraries like GraphQL Shield declare rules next to the schema. They read well and are easy to audit, and they apply to a field. They cannot see ownership of a specific row unless they call into the same data layer, so treat them as a convenience over rules, not a replacement for a place where the rules live. I did not run either approach here; both are docs-derived.

Things that quietly go wrong

  • Hiding in the UI. A button the user cannot see is not a rule. Anyone can send their own query.
  • Error messages that confirm existence. “Forbidden” versus “Not found” tells an attacker which ids exist. For private objects, return not found to both.
  • Introspection as an access list. The schema describes everything; it grants nothing.
  • Subscriptions and batch loaders. Authorization must hold for a long-lived subscription and for a DataLoader, where a cache shared across users would leak. Create loaders per request, inside the context.

The OWASP API Security Top 10 names broken object-level authorization as the first risk, and GraphQL’s many paths make it easy to hit.

What the video covers

“Authorization in GraphQL: Peanut Butter and Chocolate” is Sam Scott’s talk, published by Apollo in October 2023 and about 23 minutes long. Its chapters are: the authorization problem, defining authorization, traditional implementation, a schema-based approach, advanced architecture, handling complex queries, and conclusion. That is the second half of this lesson in depth. It is an Apollo-hosted talk, so its schema-based approach reflects Apollo’s tooling, and it spends little time on authentication proper, which is why Kevin Wade’s from-scratch auth walkthrough is under “go deeper”, alongside a graphql-shield video. I did not have a transcript.

Where this fits

With identity and permissions in place, the next problem is clients who are allowed but hostile or careless. Query depth and complexity limits puts a ceiling on what one request can cost.

Check yourself

  1. 01Why is checking permissions only in the top-level Query field not enough?

    A client can reach the same object through other fields, like author.books or a mutation payload, so each path to protected data needs the rule applied.

  2. 02Where should the token be verified and the user object built?

    In the context function, once per request, so every resolver receives the same verified user.

  3. 03What went wrong if a hidden field is returned to a user who may not see it, even though the page never shows it?

    The server leaked data. Hiding fields in the UI is not authorization, because anyone can send their own query.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark