TExcelTAD
Home › GraphQL › Authorization

Authorization

Authentication answers "who are you?" (a login, a token). Authorization answers "what may you do?". In GraphQL, authentication usually happens before execution, when the server builds the context from the request. Authorization happens during execution, in resolvers or the business logic they call, because a single query can touch many types and fields with different rules.

Where the user comes from

A typical HTTP handler verifies a token and puts the result in the context:

js
// Express / Yoga / Apollo all have a hook like this.
async function buildContext(request) {
  const token = request.headers.authorization?.replace('Bearer ', '');
  const user = token ? await verifyJwt(token) : null;   // null = anonymous
  return { user, loaders: createLoaders() };
}

Resolvers then read context.user. They never trust ids the client sends about itself.

Checks in resolvers

The most direct approach: check inside each resolver that needs it. Here anyone may list posts, only logged-in users see emails, and only admins see the audit log:

js · try it yourself
import { graphql, buildSchema, GraphQLError } from 'graphql';

const schema = buildSchema(`
  type User { name: String!, email: String }
  type Query { users: [User!]!, auditLog: [String!] }
`);

const users = [
  { name: 'Ana', email: 'ana@example.com' },
  { name: 'Ben', email: 'ben@example.com' },
];

const requireRole = (context, role) => {
  if (!context.user) throw new GraphQLError('Not logged in', { extensions: { code: 'UNAUTHENTICATED' } });
  if (!context.user.roles.includes(role)) {
    throw new GraphQLError(`Requires role ${role}`, { extensions: { code: 'FORBIDDEN' } });
  }
};

const rootValue = {
  users: () =>
    users.map((u) => ({
      name: u.name,
      // Field-level rule: hide emails from anonymous visitors.
      email: (_args, context) => (context.user ? u.email : null),
    })),
  auditLog: (_args, context) => {
    requireRole(context, 'admin');
    return ['ana changed password', 'ben logged in'];
  },
};

const viewers = {
  anonymous: null,
  member: { name: 'Ana', roles: ['member'] },
  admin: { name: 'Zoe', roles: ['member', 'admin'] },
};

for (const [label, user] of Object.entries(viewers)) {
  const result = await graphql({
    schema, rootValue, contextValue: { user },
    source: '{ users { name email } auditLog }',
  });
  console.log(label.padEnd(9), JSON.stringify(result.data), result.errors?.[0].message ?? '');
}
anonymous {"users":[{"name":"Ana","email":null},{"name":"Ben","email":null}],"auditLog":null} Not logged in
member    {"users":[{"name":"Ana","email":"ana@example.com"},{"name":"Ben","email":"ben@example.com"}],"auditLog":null} Requires role admin
admin     {"users":[{"name":"Ana","email":"ana@example.com"},{"name":"Ben","email":"ben@example.com"}],"auditLog":["ana changed password","ben logged in"]}

Note the two styles: email quietly returns null (fine for optional data), while auditLog throws an error with a code (the client should know it was denied).

Ownership rules

Role checks aren't enough for most data. "Users may only read their own orders" depends on the object being returned. The check needs the user from the context and the parent object:

js · try it yourself
import { graphql, buildSchema, GraphQLError } from 'graphql';

const schema = buildSchema(`
  type Order { id: ID!, total: Int!, ownerId: ID! }
  type Query { order(id: ID!): Order, myOrders: [Order!]! }
`);

const orders = [
  { id: 'o1', total: 40, ownerId: 'u1' },
  { id: 'o2', total: 95, ownerId: 'u2' },
  { id: 'o3', total: 12, ownerId: 'u1' },
];

// Business logic, independent of GraphQL. Reusable from REST, jobs, tests...
const orderService = {
  findVisible(id, user) {
    const order = orders.find((o) => o.id === id);
    if (!order) return null;
    if (order.ownerId !== user.id && !user.roles.includes('support')) {
      throw new GraphQLError('Not your order', { extensions: { code: 'FORBIDDEN' } });
    }
    return order;
  },
  listFor: (user) => orders.filter((o) => o.ownerId === user.id),
};

const rootValue = {
  order: ({ id }, { user }) => orderService.findVisible(id, user),
  myOrders: (_args, { user }) => orderService.listFor(user),
};

const run = async (user, source) => {
  const result = await graphql({ schema, rootValue, contextValue: { user }, source });
  console.log(`${user.id}:`, JSON.stringify(result.data), result.errors?.[0].message ?? '');
};

const u1 = { id: 'u1', roles: [] };
const agent = { id: 's9', roles: ['support'] };

await run(u1, '{ myOrders { id total } }');
await run(u1, '{ order(id: "o2") { total } }');
await run(agent, '{ order(id: "o2") { total } }');
u1: {"myOrders":[{"id":"o1","total":40},{"id":"o3","total":12}]}
u1: {"order":null} Not your order
s9: {"order":{"total":95}}

Putting the rule in orderService (not in the resolver) is the pattern the GraphQL docs recommend: there is then exactly one place that decides who sees an order, whether the request comes through GraphQL, REST or a background job.

Wrapping resolvers

Writing the same check in many resolvers is repetitive. A small higher-order function keeps it declarative:

js · try it yourself
import { graphql, buildSchema, GraphQLError } from 'graphql';

const authenticated = (resolve) => (args, context, info) => {
  if (!context.user) throw new GraphQLError('Not logged in', { extensions: { code: 'UNAUTHENTICATED' } });
  return resolve(args, context, info);
};

const schema = buildSchema(`type Query { publicStats: Int, myInbox: [String!] }`);

const rootValue = {
  publicStats: () => 1024,
  myInbox: authenticated((_args, { user }) => [`Welcome back, ${user.name}!`]),
};

for (const user of [null, { name: 'Ana' }]) {
  const result = await graphql({ schema, rootValue, contextValue: { user }, source: '{ publicStats myInbox }' });
  console.log(JSON.stringify(result.data), result.errors ? result.errors[0].extensions.code : 'ok');
}
{"publicStats":1024,"myInbox":null} UNAUTHENTICATED
{"publicStats":1024,"myInbox":["Welcome back, Ana!"]} ok

Libraries take this further: schema directives (@auth(requires: ADMIN)), graphql-shield rule maps, or Pothos' auth plugin.

Common mistakes

  • Trusting arguments for identity: orders(userId: "u2") lets anyone read anyone's orders. Use context.user.
  • Only checking the root field: if Order.customer.paymentMethods is sensitive, nested resolvers need rules too, because clients can reach a type through many paths.
  • Hiding instead of authorizing: removing a field from your UI or disabling introspection doesn't protect it.
  • Shared caches across users: a DataLoader or response cache keyed only by id may serve data loaded for another user.

Test yourself

Where is the authenticated user usually placed for resolvers to read?

  1. In a query argument
  2. In the context
  3. In the root value
  4. In a global variable

Why put ownership rules in a business-logic layer instead of each resolver?

  1. Resolvers can't throw errors
  2. So one function decides access for every entry point (GraphQL, REST, jobs)
  3. It's faster
  4. GraphQL forbids logic in resolvers

Is orders(userId: ID!) a safe way to show a user their own orders?

  1. Yes, if the field is non-null
  2. No, any client could pass another user's id
  3. Yes, if introspection is off
  4. Only with fragments