Thuta Learning
GraphQL
AdvancedWeb Developmentbeginner

Auth in GraphQL — Authentication and Authorization

What you'll walk away with

  • Explain the core ideas behind Auth in GraphQL — Authentication and Authorization
  • Run the sample GraphQL query or code and verify its output
  • Apply the technique correctly to the Tutorial Platform and production scenarios

Build the mental model

GraphQL schemas have no built-in auth mechanism: authentication (who is this) happens once during context creation by decoding a token, while authorization (can this user do this) must be an explicit check written into each resolver that needs it. Throw unauthenticated or unauthorized failures as `GraphQLError` with `extensions.code: 'UNAUTHENTICATED'` or `'FORBIDDEN'` so the client can distinguish them.

Connect it to a real scenario

Inside the `deleteTutorial` mutation resolver, throw `UNAUTHENTICATED` immediately if `context.userId` is missing, and throw `FORBIDDEN` if the user lacks the `editor` role — both checks must run before the database delete is called.

Try the working example

typescript
const resolvers = {
  Mutation: {
    deleteTutorial: (
      _parent: unknown,
      args: { id: string },
      context: Context,
    ) => {
      if (!context.userId) {
        throw new GraphQLError('You must be logged in', {
          extensions: { code: 'UNAUTHENTICATED' },
        });
      }
      if (!context.roles.includes('editor')) {
        throw new GraphQLError('Editors only', {
          extensions: { code: 'FORBIDDEN' },
        });
      }
      return tutorialRepository.delete(args.id);
    },
  },
};
You should see
You can correctly write both authentication and authorization checks inside a resolver.

5-minute try-it

Write the `publishTutorial` mutation with an authorization rule allowing an `author` (own tutorials only) or an `editor` (any tutorial).

One important caution

Do not enforce authorization only in the frontend UI (hiding a button) without a server-side check in the resolver — anyone can send a raw GraphQL request, so server-side enforcement is mandatory.

Apollo Server — Authentication and AuthorizationGraphQL

Easy traps

  • Do not enforce authorization only in the frontend UI (hiding a button) without a server-side check in the resolver — anyone can send a raw GraphQL request, so server-side enforcement is mandatory.
  • Validate sample queries and mutations on a local or test server with recoverable data before applying them to production.

Exercise

Write the `publishTutorial` mutation with an authorization rule allowing an `author` (own tutorials only) or an `editor` (any tutorial).

You'll know it worked when: You can correctly write both authentication and authorization checks inside a resolver.

Auth in GraphQL — Authentication and Authorization | Thuta Learning