Skip to main content

GraphQL Security Cheat Sheet

Securing your GraphQL APIs? Access the ultimate GraphQL Security Cheat Sheet for quick, actionable tips on prevention, rate limiting, queries depth, and authorization.

Updated 15 min readMarkdown
GraphQL Security Cheat Sheet

Table of Contents

  1. Introduction
  2. Common GraphQL Security Threats
  3. Input Validation
  4. Injection Prevention
  5. Denial of Service (DoS) Prevention
  6. Query Depth and Amount Limiting
  7. Query Timeouts
  8. Query Cost Analysis
  9. Rate Limiting
  10. Server-Side Batching and Caching
  11. System Resource Management
  12. Access Control
  13. Object-Level Authorization
  14. Field-Level Authorization
  15. Mutation Authorization
  16. GraphQL Batching Attacks
  17. Mitigating Batching Attacks
  18. Secure Configuration
  19. Introspection and GraphiQL
  20. Error Handling
  21. Security Checklist
  22. References

1. Introduction

GraphQL is an open-source query language originally developed by Facebook. It provides an alternative to REST and SOAP for building APIs.

GraphQL has gained popularity because of the flexibility it offers to API developers and consumers. It allows clients to request specific data through a single endpoint.

However, this flexibility introduces security challenges, including injection attacks, excessive resource consumption, broken authorization, and batching attacks.

This cheat sheet covers the essential security controls required to build secure GraphQL APIs.

1.1 Core Security Principles

  1. Validate all incoming data.
  2. Limit expensive queries to prevent Denial of Service (DoS).
  3. Enforce proper access control.
  4. Disable insecure default configurations.
  5. Restrict excessive error messages and debugging information.
  6. Monitor and control GraphQL batching.

2. Common GraphQL Security Threats

GraphQL APIs can be vulnerable to several types of attacks.

Threat Description
SQL Injection Malicious input manipulates database queries.
NoSQL Injection Malicious input changes the behavior of NoSQL queries.
OS Command Injection User input influences operating system commands.
SSRF User-controlled input causes requests to unintended destinations.
CRLF Injection Malicious input introduces unexpected HTTP headers or responses.
Request Smuggling Inconsistent HTTP request parsing can allow requests to be manipulated.
Denial of Service Expensive queries consume excessive server resources.
Broken Authorization Users access or modify data they are not permitted to access.
IDOR Direct object identifiers are used to access unauthorized resources.
Batching Attacks Multiple operations are combined to bypass request-level controls.
Insecure Configuration Debugging, introspection, or schema exploration exposes unnecessary information.

3. Input Validation

Strict input validation helps prevent injection attacks and excessive resource consumption.

GraphQL applications frequently use client-provided identifiers in database queries, HTTP requests, and other backend operations.

These inputs must be validated before being used.

3.1 General Practices

  1. Validate all incoming data using allowlists.
  2. Use specific GraphQL types, such as scalars and enums.
  3. Define schemas for mutation inputs.
  4. Create custom validators for complex validation requirements.
  5. Use custom scalars where appropriate.
  6. Define allowed characters instead of relying on denylists.
  7. Use a consistent internal character encoding when handling Unicode.
  8. Reject invalid input without revealing excessive implementation details.

3.2 Example: Mutation Input Validation

input CreateUserInput {
  username: String!
  email: String!
  age: Int!
}

type Mutation {
  createUser(input: CreateUserInput!): User
}

The schema defines the expected input structure.

However, GraphQL type validation alone is not sufficient. The application must also validate business rules, such as acceptable usernames, email formats, and age ranges.

4. Injection Prevention

GraphQL resolvers often pass user input to other interpreters, including:

  • SQL and NoSQL databases
  • ORMs and ODMs
  • Operating system commands
  • LDAP
  • XML processors

4.1 Security Recommendations

  1. Use libraries and APIs that support safe parameter handling.
  2. Prefer parameterized database queries.
  3. Use ORMs and ODMs correctly.
  4. Avoid constructing queries through string concatenation.
  5. Follow the documentation for the libraries and frameworks you use.
  6. When safe APIs are unavailable, apply appropriate escaping or encoding for the target interpreter.
  7. Use well-maintained libraries for escaping and encoding.

4.2 Example: Parameterized SQL

const query = `
  SELECT *
  FROM users
  WHERE id = $1
`;

const result = await db.query(query, [userId]);

Parameterized queries help prevent user input from being interpreted as SQL syntax.

4.3 Process Validation

Even validated or sanitized input should not be allowed to control sensitive data flows.

For example, avoid making HTTP requests to arbitrary hosts supplied by users unless there is an explicit business requirement.

This helps reduce the risk of Server-Side Request Forgery (SSRF).

5. Denial of Service (DoS) Prevention

GraphQL queries can request deeply nested objects or large amounts of data.

Without appropriate controls, a single request can consume excessive CPU, memory, database connections, or downstream service resources.

  1. Limit query depth.
  2. Limit the number of objects requested.
  3. Implement pagination.
  4. Configure reasonable timeouts.
  5. Enforce query cost limits where appropriate.
  6. Apply rate limiting per IP address, user, or both.
  7. Implement server-side batching and caching.
  8. Restrict application and infrastructure resource consumption.

6. Query Depth and Amount Limiting

GraphQL queries can contain nested relationships.

Without restrictions, a query can request deeply nested objects or an excessive number of records.

6.1 Query Depth Limiting

Consider the following query:

query {
  album(id: 42) {
    songs {
      album {
        songs {
          album {
            songs {
              title
            }
          }
        }
      }
    }
  }
}

The query depth increases with each nested object.

Excessive nesting can cause expensive resolver execution and database queries.

Recommendation: Define and enforce a maximum query depth.

6.2 Query Amount Limiting

Consider this query:

query {
  author(id: "abc") {
    posts(first: 99999999) {
      title
    }
  }
}

The client requests an extremely large number of posts.

Recommendation:

  1. Set maximum limits for collection arguments.
  2. Enforce pagination.
  3. Reject requests exceeding the configured limits.
  4. Apply limits to nested collections as well.

6.3 Implementation Options

For Java:

  • MaxQueryDepthInstrumentation from graphql-java.

For JavaScript:

  • graphql-depth-limit
  • graphql-input-number

Implementation details depend on the GraphQL server and framework.

7. Query Timeouts

Timeouts limit how long a request or resolver can consume resources.

7.1 Application-Level Timeouts

Application-level timeouts can stop query execution or resolver processing when a defined limit is exceeded.

GraphQL does not natively provide a universal query timeout mechanism.

Custom implementation may be required.

7.2 Example: JavaScript Timeout Check

request.incrementResolverCount = function () {
  const runtime = Date.now() - startTime;

  if (runtime > 10000) {
    throw new Error("Query execution timeout");
  }

  this.resolverCount++;
};

This example demonstrates a timeout check during resolver execution.

A production implementation should use the server's supported cancellation and timeout mechanisms where available.

7.3 Infrastructure-Level Timeouts

Timeouts can also be configured in:

  1. HTTP servers
  2. Reverse proxies
  3. Load balancers
  4. Application infrastructure

Infrastructure-level timeouts are useful as an additional control, but they may not stop expensive application work immediately.

Recommendation: Use application-level timeouts together with infrastructure-level limits.

8. Query Cost Analysis

Query cost analysis assigns a cost to fields, types, or operations within a GraphQL query.

The server can reject queries that exceed a defined cost threshold.

8.1 Why Query Cost Matters

Two queries with the same depth can have very different execution costs.

For example, a query requesting a single user is generally less expensive than a query requesting thousands of users, each with multiple nested relationships.

8.2 Recommendations

  1. Assign costs to expensive fields and operations.
  2. Account for nested collections.
  3. Define a maximum allowed query cost.
  4. Reject queries that exceed the configured limit.
  5. Test expensive queries in a staging environment before introducing complex cost-analysis logic.

8.3 Implementation Options

For Java:

  • MaxQueryComplexityInstrumentation from graphql-java.

For JavaScript:

  • graphql-cost-analysis
  • graphql-validation-complexity

Query cost analysis can be useful for APIs with complex relationships or expensive data-fetching operations.

However, it should be implemented based on the actual resource-consumption risks of the API.

9. Rate Limiting

Rate limiting restricts how frequently a client can make requests.

9.1 Network-Level Rate Limiting

Limit incoming HTTP requests per client using mechanisms such as:

  • Nginx limit_req
  • API gateways
  • Reverse proxies

Apache's mod_ratelimit limits response bandwidth; it does not limit incoming request counts.

9.2 GraphQL-Specific Rate Limiting

HTTP request counts alone are insufficient for GraphQL.

A single request can contain multiple operations or request many objects.

Recommendation:

  1. Apply rate limits at the business logic layer.
  2. Consider query cost when determining request limits.
  3. Restrict the number of batched operations.
  4. Apply limits per user or authenticated client.
  5. Combine rate limiting with query depth and amount limits.

10. Server-Side Batching and Caching

GraphQL applications can use batching and caching to reduce duplicate data-fetching operations.

For example, multiple resolvers may request the same user or related database record.

Without batching, these operations may generate unnecessary database queries.

10.1 DataLoader

Facebook's DataLoader is one option for implementing batching and caching.

It can help:

  1. Combine multiple data-fetching operations.
  2. Reduce duplicate requests.
  3. Improve resolver efficiency.
  4. Reduce unnecessary backend resource consumption.

Batching and caching should be implemented carefully, especially when data access depends on the authenticated user or tenant.

11. System Resource Management

GraphQL APIs must restrict the amount of system resources they can consume.

Unrestricted resource consumption can affect API availability and responsiveness.

  1. Apply CPU and memory limits.
  2. Restrict process and file resource usage.
  3. Configure appropriate database connection limits.
  4. Monitor resource consumption.
  5. Use operating system resource controls where appropriate.
  6. Apply container resource limits.

On Linux, resource management can include:

  • Control Groups (cgroups)
  • User Limits (ulimits)
  • Linux Containers (LXC)

Containerization platforms can simplify resource management.

12. Access Control

GraphQL APIs must verify that the requester is authorized to access or modify the requested data.

12.1 Authorization Recommendations

  1. Validate authorization for every requested object.
  2. Enforce authorization for both reads and mutations.
  3. Use RBAC or another appropriate access control mechanism.
  4. Validate authorization on both edges and nodes.
  5. Use structured types to expose only permitted properties.
  6. Implement authorization checks in resolvers or appropriate middleware.
  7. Disable introspection in production or publicly accessible environments when appropriate.
  8. Disable GraphiQL and similar schema exploration tools in production or publicly accessible environments when appropriate.

13. Object-Level Authorization

GraphQL APIs frequently accept direct object identifiers.

For example:

query {
  user(id: "123") {
    name
    email
  }
}

A common security mistake is assuming that possession of an object ID means the requester is authorized to access it.

This can result in Broken Object Level Authorization (BOLA), also known as IDOR.

13.1 Security Recommendations

  1. Verify that the requester can access the requested object.
  2. Apply authorization checks to direct object lookups.
  3. Protect node and nodes fields where they exist.
  4. Avoid relying on unpredictable identifiers as an authorization mechanism.
  5. Apply authorization consistently across all data-fetching paths.

13.2 Example

async function getUser(userId, context) {
  const user = await db.user.findUnique({
    where: { id: userId }
  });

  if (!user) {
    return null;
  }

  if (user.id !== context.user.id) {
    throw new Error("Not authorized");
  }

  return user;
}

This is a simplified example. Real applications may require role-based, tenant-based, or resource-specific authorization rules.

14. Field-Level Authorization

GraphQL APIs may expose fields with different permission requirements.

For example, a user may be allowed to view a customer's name but not their billing information.

14.1 Recommendations

  1. Identify fields requiring restricted access.
  2. Validate the requester's permissions before returning sensitive fields.
  3. Apply authorization checks consistently across resolvers.
  4. Use structured data types to expose different properties according to permissions.

Authorization should not depend solely on hiding fields in the client application.

15. Mutation Authorization

GraphQL mutations allow clients to create, update, or delete data.

If a mutation is not properly protected, an attacker may modify data they should only be able to read or should not access at all.

15.1 Recommendations

  1. Restrict mutations to authorized users.
  2. Verify permissions for the target object.
  3. Validate which fields the requester can modify.
  4. Enforce business rules on the server.
  5. Prevent unauthorized access to sensitive mutations.

For APIs where only read access is intended, mutation operations should not be exposed to unauthorized consumers.

16. GraphQL Batching Attacks

GraphQL supports batching multiple queries or operations into a single network request.

This feature can be abused to perform brute-force attacks, enumerate objects, or exhaust resources.

16.1 Example: Batched Requests

[
  {
    "query": "query { user(id: \"1001\") { name } }"
  },
  {
    "query": "query { user(id: \"1002\") { name } }"
  },
  {
    "query": "query { user(id: \"1003\") { name } }"
  }
]

An attacker may use batching to request many objects in a single HTTP request.

16.2 Potential Risks

  1. Application-level Denial of Service.
  2. Enumeration of users, emails, and object identifiers.
  3. Brute-force attacks against passwords, OTPs, or session tokens.
  4. Bypassing request-level rate limits.
  5. Reduced visibility in monitoring and security tools.

A single HTTP request may contain many operations, making ordinary request-count-based controls insufficient.

17. Mitigating Batching Attacks

17.1 Object Request Rate Limiting

Track the number of object instances requested by each caller.

Reject requests when the caller exceeds the allowed number of object requests, even if those requests are batched into a single network call.

17.2 Restrict Batching for Sensitive Objects

Consider preventing batching for sensitive operations involving:

  • Usernames
  • Email addresses
  • Passwords
  • OTPs
  • Session tokens

This can make brute-force attempts more difficult to perform through a single request.

17.3 Limit Concurrent Operations

Restrict the number of operations that can execute simultaneously.

This helps reduce resource exhaustion but should be combined with other controls.

  1. Implement application-level object request limits.
  2. Restrict batching for sensitive operations.
  3. Limit the number of operations per request.
  4. Apply query cost and rate limits.
  5. Monitor suspicious patterns of batched requests.

18. Secure Configuration

GraphQL implementations may include insecure default configurations.

These should be reviewed before deploying an API to production.

18.1 Configuration Recommendations

  1. Disable excessive error messages.
  2. Disable stack traces in production responses.
  3. Disable debug mode in production.
  4. Disable or restrict introspection.
  5. Disable or restrict GraphiQL.
  6. Review schema suggestions and error hints.
  7. Restrict schema exploration to authorized consumers.

19. Introspection and GraphiQL

GraphQL introspection allows clients to discover the API schema.

GraphiQL provides an interactive environment for exploring and executing GraphQL queries.

These features can expose information about:

  • Types
  • Fields
  • Mutations
  • Deprecated fields
  • Internal API structure

19.1 Security Recommendations

  1. Disable introspection in production when it is not required.
  2. Restrict introspection to authenticated or authorized users when necessary.
  3. Disable GraphiQL in production or publicly accessible environments.
  4. Avoid exposing internal schema information unnecessarily.
  5. Review whether schema suggestions reveal additional information.

Disabling introspection is not a replacement for proper authorization.

Attackers may still discover field names through other methods, including brute-force attempts.

19.2 Java Example: Disable Introspection

GraphQLSchema schema = GraphQLSchema.newSchema()
    .query(StarWarsSchema.queryType)
    .fieldVisibility(
        NoIntrospectionGraphqlFieldVisibility
            .NO_INTROSPECTION_FIELD_VISIBILITY
    )
    .build();

This example demonstrates disabling introspection through field visibility in graphql-java.

19.3 JavaScript Example: Restrict Introspection and GraphiQL

app.use('/graphql', graphqlHTTP({
  schema: MySessionAwareGraphQLSchema,
  validationRules: [NoIntrospection],
  graphiql: process.env.NODE_ENV === 'development',
}));

This example assumes an introspection-denying validation rule is available.

For new applications, use a maintained GraphQL server implementation and follow its current configuration guidance.

20. Error Handling

GraphQL APIs should not expose unnecessary internal information through error responses.

Excessive error details can reveal implementation information that helps attackers understand the application.

20.1 Recommendations

  1. Disable stack traces in production responses.
  2. Disable debug mode.
  3. Avoid exposing database errors.
  4. Mask internal errors before returning them to clients.
  5. Log detailed errors internally for debugging and monitoring.
  6. Review field suggestions and validation errors.

20.2 Apollo Server Example

const server = new ApolloServer({
  includeStacktraceInErrorResponses: false,
});

This option disables stack traces in error responses.

Error messages may still require separate masking.

21. Security Checklist

Use this checklist when reviewing a GraphQL API.

Input Validation

  • Validate all incoming data.
  • Use allowlists and appropriate GraphQL types.
  • Define mutation input schemas.
  • Use parameterized database queries.
  • Prevent user input from controlling sensitive data flows.

DoS Prevention

  • Enforce query depth limits.
  • Enforce query amount limits.
  • Implement pagination.
  • Configure application-level timeouts.
  • Apply query cost limits where appropriate.
  • Implement rate limiting.
  • Restrict resource consumption.
  • Review batching and caching.

Access Control

  • Enforce object-level authorization.
  • Enforce field-level authorization.
  • Enforce mutation authorization.
  • Protect direct object lookups.
  • Review node and nodes access.
  • Prevent IDOR and BOLA vulnerabilities.

Batching Protection

  • Limit operations per request.
  • Restrict batching for sensitive objects.
  • Apply object-level request limits.
  • Monitor suspicious batching behavior.

Secure Configuration

  • Disable unnecessary introspection.
  • Disable GraphiQL in production.
  • Disable debug mode.
  • Remove stack traces from production responses.
  • Review schema suggestions and error messages.

22. References

  1. OWASP GraphQL Cheat Sheet
  2. OWASP Input Validation Cheat Sheet
  3. OWASP SQL Injection Prevention Cheat Sheet
  4. OWASP NoSQL Security Cheat Sheet
  5. graphql-java Documentation
  6. DataLoader

Final Note: GraphQL's flexibility is powerful, but it must be supported by strict validation, authorization, resource limits, and secure configuration. Treat every query, mutation, and resolver as a potential security boundary.

About the author

No comments yet. Be the first to comment.