Graphql auth patterns

From Intense-Visions/harness-engineering · View interactive version

Graphql auth patterns is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Implement authentication and authorization in GraphQL with context-based identity, directives, and field-level guards

How to use this skill

Skill file

GraphQL Auth Patterns

Implement authentication and authorization in GraphQL with context-based identity, directives, and field-level guards

When to Use

Instructions

  1. Authenticate in the context factory, not in resolvers. Extract and verify the auth token during context creation. Every resolver then has access to context.currentUser without re-authenticating.
const server = new ApolloServer({ typeDefs, resolvers });

app.use(
  '/graphql',
  expressMiddleware(server, {
    context: async ({ req }) => {
      const token = req.headers.authorization?.replace('Bearer ', '');
      const currentUser = token ? await verifyJWT(token) : null;
      return { currentUser };
    },
  })
);
  1. Create a reusable auth guard function that resolvers call to check permissions. This keeps authorization logic in one place.
function requireAuth(context: Context): AuthenticatedUser {
  if (!context.currentUser) {
    throw new GraphQLError('Authentication required', {
      extensions: { code: 'UNAUTHENTICATED' },
    });
  }
  return context.currentUser;
}

function requireRole(context: Context, role: string): AuthenticatedUser {
  const user = requireAuth(context);
  if (!user.roles.includes(role)) {
    throw new GraphQLError('Insufficient permissions', {
      extensions: { code: 'FORBIDDEN' },
    });
  }
  return user;
}
  1. Use schema directives for declarative auth. Define @auth and @hasRole directives to annotate the schema. Implement them as schema transforms.
directive @auth on FIELD_DEFINITION | OBJECT
directive @hasRole(role: String!) on FIELD_DEFINITION

type Query {
  me: User @auth
  adminDashboard: Dashboard @hasRole(role: "ADMIN")
  publicPosts: [Post!]!
}

type User @auth {
  id: ID!
  email: String!
  role: String!
}
  1. Implement directive transforms using @graphql-tools/utils.
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';

function authDirectiveTransformer(schema: GraphQLSchema) {
  return mapSchema(schema, {
    [MapperKind.OBJECT_FIELD]: (fieldConfig) => {
      const authDirective = getDirective(schema, fieldConfig, 'auth')?.[0];
      const roleDirective = getDirective(schema, fieldConfig, 'hasRole')?.[0];

      if (authDirective || roleDirective) {
        const originalResolve = fieldConfig.resolve ?? defaultFieldResolver;
        fieldConfig.resolve = async (source, args, context, info) => {
          if (roleDirective) {
            requireRole(context, roleDirective.role);
          } else {
            requireAuth(context);
          }
          return originalResolve(source, args, context, info);
        };
      }
      return fieldConfig;
    },
  });
}
  1. Authorize at the data layer for defense in depth. Even with resolver-level guards, validate ownership and access in data source methods. This prevents bypasses when resolvers are added or modified.
class OrderDataSource {
  async findById(id: string, currentUser: User): Promise<Order> {
    const order = await this.db.orders.findUnique({ where: { id } });
    if (!order) throw new NotFoundError('Order');
    if (order.userId !== currentUser.id && !currentUser.roles.includes('ADMIN')) {
      throw new ForbiddenError('Not authorized to view this order');
    }
    return order;
  }
}
  1. Filter fields based on permissions when needed. Some fields should be visible only to certain roles (e.g., User.email visible to admins and the user themselves).
const resolvers = {
  User: {
    email: (user, _args, { currentUser }) => {
      if (currentUser?.id === user.id || currentUser?.roles.includes('ADMIN')) {
        return user.email;
      }
      return null; // or throw, depending on your schema nullability
    },
  },
};
  1. Protect against query depth and complexity attacks. Authenticated users can still submit expensive queries. Use query depth limiting and cost analysis.
import depthLimit from 'graphql-depth-limit';
import { createComplexityLimitRule } from 'graphql-validation-complexity';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [depthLimit(10), createComplexityLimitRule(1000)],
});
  1. Return UNAUTHENTICATED for missing credentials and FORBIDDEN for insufficient permissions. This distinction helps clients show the right UI (login prompt vs. access denied).

Details

Authentication vs. authorization: Authentication answers "who are you?" (JWT verification, session lookup). Authorization answers "can you do this?" (role checks, ownership validation). Keep them separate — authenticate once in context, authorize per field/mutation.

Auth approaches compared:

graphql-shield example:

import { shield, rule, allow } from 'graphql-shield';

const isAuthenticated = rule()((parent, args, { currentUser }) => currentUser !== null);
const isAdmin = rule()((parent, args, { currentUser }) => currentUser?.roles.includes('ADMIN'));

const permissions = shield({
  Query: { '*': isAuthenticated, publicPosts: allow },
  Mutation: { deleteUser: isAdmin },
});

Common mistakes:

Source

https://www.apollographql.com/docs/apollo-server/security/authentication/

Process

  1. Read the instructions and examples in this document.
  2. Apply the patterns to your implementation, adapting to your specific context.
  3. Verify your implementation against the details and edge cases listed above.

Harness Integration

Success Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.