Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy GraphQL Security
Advanced · 25 min

GraphQL Security

Understand GraphQL introspection exposure, missing field-level authorization, and query depth attacks.

1 GraphQL Attack Vectors

GraphQL APIs have unique security challenges beyond traditional REST APIs.

1. Introspection exposure:

# Attacker queries the entire schema
{ __schema { types { name fields { name type { name } } } } }
# Returns: all types, fields, mutations, and their arguments
# Enables targeted attack planning

2. Missing field-level authorization:

query {
  user(id: "123") {
    email        # Public — OK
    passwordHash # Should be restricted — but is it?
    adminNotes   # Internal field exposed to all authenticated users!
  }
}

3. Query depth attacks (DoS):

{ user { friends { friends { friends { friends { posts { comments { author { friends { ... } } } } } } } } } }
# Exponentially complex query — can exhaust server memory

4. Batching attacks: GraphQL allows multiple operations in one request, enabling enumeration attacks at scale.

2 GraphQL Hardening

Harden GraphQL APIs with introspection controls, depth limiting, and field-level authorization.

Disable introspection in production:

const { ApolloServer } = require("@apollo/server");

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: process.env.NODE_ENV !== "production",  // Off in prod
});

Query depth limiting:

const depthLimit = require("graphql-depth-limit");

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [depthLimit(5)],  // Max 5 levels of nesting
});

Field-level authorization with shield:

const { shield, rule } = require("graphql-shield");

const isAdmin = rule()((parent, args, ctx) => ctx.user?.role === "admin");

const permissions = shield({
  User: {
    passwordHash: isAdmin,    // Only admins can query this field
    adminNotes: isAdmin,
    email: allow,             // Public
  }
});

Knowledge Check

0/3 correct
Q1

Why is enabling GraphQL introspection in production dangerous?

Q2

What is a GraphQL depth attack?

Q3

How does field-level authorization differ from type-level authorization in GraphQL?

Code Exercise

Disable GraphQL Introspection in Production

The GraphQL server enables introspection in all environments. Fix it to disable introspection when NODE_ENV is "production".

javascript