Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Security and Performance

Authentication and Authorization

Secure a GraphQL API: authenticate once in HTTP middleware, put the user in context, enforce rules in the business layer, and control access per field.

GraphQL has no built-in login and no built-in permissions. The specification says nothing about who is allowed to ask for what, and that is on purpose: security depends on your product. Because one endpoint serves every query and clients choose their own fields, though, getting access control wrong is easy. A forgotten check in one resolver is a hole that any client can find by typing a query.

This lesson separates two ideas that people often mix up. Authentication answers "who is making this request?" Authorization answers "is this person allowed to do this?" Handle them in different places.

Reminder: no real GraphQL server runs on this site, and the real token and session setup below is read-only. The runnable examples are stand-ins: a small executor with a fake HTTP layer, and plain functions that show how field rules work.

Two different questions

Authentication Who are you? Checked once per request.
Authorization May you do this? Checked wherever data is used.

Authentication feeds the context; authorization reads it.

1 / 2

Authenticate once, outside GraphQL

Do not log users in inside resolvers, and do not check tokens field by field. Authenticate once per HTTP request, in middleware or in the function that builds the context, before any GraphQL runs. The usual credential is a token in the Authorization header, or a session cookie. The server verifies it and either finds a user or finds none.

Typical handling:

  • No credentials: the request is anonymous. Many APIs allow this, because public fields (a product list) need no login.
  • Valid credentials: put the user object into the context (the third argument of every resolver; see Resolvers).
  • Invalid or expired credentials: reject the whole request with HTTP 401 before running the query. Do not silently treat it as anonymous, or a user with an expired token sees confusing "empty" data.

Read-only, here is how that looks with a real Node server and the jsonwebtoken package (a sketch, not a complete app):

JavaScript
import jwt from "jsonwebtoken";

async function buildContext(req) {
  const header = req.headers.authorization;
  if (!header) return { user: null };

  const token = header.replace(/^Bearer /, "");
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET); // checks signature and expiry
    return { user: await db.users.findById(payload.sub) };
  } catch {
    throw new HttpError(401, "Invalid or expired token");
  }
}

If you use cookie sessions instead of bearer tokens, the browser sends the cookie automatically, which means other websites can make the browser send requests to your API. Add CSRF protection (for example, require a custom header or a CSRF token, and set SameSite on the cookie), and make sure GET requests cannot run mutations.

The stand-in below builds the full path with a fake HTTP layer. The executor is a hand-written one that supports arguments, resolvers with a (parent, args, context) signature, and error codes. The part to study is at the bottom: authenticate runs first and its result becomes the context.

Node.js Authentication in the HTTP layer, rules in a service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the seven responses:

  • The anonymous request sees only published posts, and me is simply null, not an error. Not being logged in is a normal state.
  • Ana is an editor. She cannot see the draft by someone else: post(id: 3) returns null and an error with the code FORBIDDEN, at the path ["post"].
  • Asking for internalNotes as an editor produces one FORBIDDEN error per post, with the rest of the data intact, because that field is nullable (see How Execution Works and How Errors Behave).
  • Root, the admin, sees everything.
  • The bad token never reaches GraphQL: HTTP 401 with an UNAUTHENTICATED code.

Authorize in the business layer

Look again at the resolvers in the stand-in. They contain no rules at all:

JavaScript
posts: { type: "[Post!]!", resolve: (_, args, ctx) => postService.list(ctx.user) },

All decisions are in postService: who can see a draft, who can read notes. That is the principle to remember. Put authorization in the layer that owns the data (services, models, policies), not in each resolver. The reasons:

  1. A GraphQL API is rarely the only entry point. A REST route, a background job or a command line script calls the same service, and they all get the same rules.
  2. The same object can be reached by many paths: Query.post, User.posts, Comment.post, a search result. Each resolver that returns a post would need its own copy of the check, and the one you forget is the leak.
  3. Rules are easier to test and read in one place than scattered across 200 resolvers.

A resolver should only pass the current user (from context) and the arguments to the service, and the service either returns data the user may see or throws.

Never treat "the client didn't ask for it" or "the UI doesn't show it" as a security measure. Any client can send any query that the schema allows. Introspection even lists the field names. Enforce rules on the server, always.

Authorizing objects, not only queries

Checking the root field is not enough. A rule like "users may only see their own orders" must hold also when an order is reached through user { orders }, invoice { order } or a search. Check at the point where an object is loaded or returned, by passing the user into the data access code (for example, a query that always filters by owner_id = :userId). That is why services and loaders take the user: if you use DataLoader (The N+1 Problem and DataLoader), create the loaders per request with the user bound in, so a cached object is never shared with someone who may not see it.

Field-level rules

Sometimes the same type is visible to many people, but a few fields are sensitive: an employee's salary, a customer's email. There are two approaches to treat such a field.

Enforce at resolve time. The field exists in the schema for everyone, but a forbidden caller gets null and an error (like internalNotes above). Make the field nullable, or the error bubbles up and blanks the parent object.

Hide at validation time. The field does not exist for that caller: asking for it fails as an unknown field, which also keeps it out of that caller's introspection results. This is achieved by serving different schemas per audience (public API and admin API), or by a library feature that filters the schema for each request.

The following stand-in shows both ways on the same set of rules, kept as plain data. No GraphQL library is involved; it only illustrates the difference in outcome.

Node.js Enforcing versus hiding fields per role

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For a guest, "enforced" returns the name and an error for each sensitive field, while "hidden" says those fields do not exist. Enforcing is simpler and gives helpful messages. Hiding reveals less, but is more work, and a careless message such as "field exists but is forbidden" leaks the same information anyway.

Directives

Rules attached to fields can also be written in the schema as a directive, a custom annotation. This is a common style in some ecosystems:

GRAPHQL
directive @auth(requires: Role = USER) on OBJECT | FIELD_DEFINITION

enum Role {
  USER
  SUPPORT
  ADMIN
}

type Employee {
  name: String!
  email: String! @auth(requires: SUPPORT)
  salary: Int @auth(requires: ADMIN)
}

type Mutation {
  deleteEmployee(id: ID!): Boolean @auth(requires: ADMIN)
}

The rule is visible next to the field, which is good documentation. A directive does nothing by itself, though. Your server library must implement it, typically by wrapping the field's resolver the way the stand-in's resolveField does. Directives are good for coarse role checks ("admins only"). Rules that depend on the object (this order belongs to you) usually need code in the service, because a directive does not know about the data.

A short checklist

  • Authenticate in middleware; put user (or null) in the context; return 401 for bad credentials.
  • Pass the user to services; keep policy in one layer; test it.
  • Give nullable types to fields that may be forbidden.
  • Check every path to an object, including nested ones and mutations.
  • Do not return secrets in error messages, and use codes (UNAUTHENTICATED, FORBIDDEN) in extensions.
  • Combine with the limits from Query Depth, Complexity and Other Attacks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should the token or session cookie normally be verified?

    Authentication happens once in middleware or context creation. Resolvers then read the user from the context.
  2. 2. Why put authorization rules in a service layer instead of in each resolver?

    A single place for rules prevents a forgotten check on one of many paths and also protects REST routes and jobs that use the service.
  3. 3. A request arrives with an expired token. What is the better behavior?

    Silently downgrading to anonymous hides the real problem from the client. A clear 401 lets it refresh the token.
  4. 4. A sensitive field is enforced at resolve time. Why should its type be nullable?

    A forbidden non-null field would force the null to move up to the nearest nullable parent, so one denied field could blank a whole object.
  5. 5. What does a custom @auth directive do on its own?

    A directive is only an annotation. The server library must give it behavior.

Summary

  • Authentication ("who?") runs once per HTTP request and puts the user, or null, in the context; bad credentials get HTTP 401.
  • Authorization ("may they?") belongs in the business layer so every path to the data obeys the same rules.
  • Check access wherever an object is loaded, not only at root fields, and never rely on the client.
  • Enforce field rules at resolve time (nullable field plus FORBIDDEN) or hide fields per audience.
  • Directives document rules but need server code to enforce them.
  • Use stable codes such as UNAUTHENTICATED and FORBIDDEN, and never leak secrets in messages.

Next: Query Depth, Complexity and Other Attacks.