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.

Table of Contents
- Introduction
- Common GraphQL Security Threats
- Input Validation
- Injection Prevention
- Denial of Service (DoS) Prevention
- Query Depth and Amount Limiting
- Query Timeouts
- Query Cost Analysis
- Rate Limiting
- Server-Side Batching and Caching
- System Resource Management
- Access Control
- Object-Level Authorization
- Field-Level Authorization
- Mutation Authorization
- GraphQL Batching Attacks
- Mitigating Batching Attacks
- Secure Configuration
- Introspection and GraphiQL
- Error Handling
- Security Checklist
- 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
- Validate all incoming data.
- Limit expensive queries to prevent Denial of Service (DoS).
- Enforce proper access control.
- Disable insecure default configurations.
- Restrict excessive error messages and debugging information.
- 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
- Validate all incoming data using allowlists.
- Use specific GraphQL types, such as scalars and enums.
- Define schemas for mutation inputs.
- Create custom validators for complex validation requirements.
- Use custom scalars where appropriate.
- Define allowed characters instead of relying on denylists.
- Use a consistent internal character encoding when handling Unicode.
- 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
- Use libraries and APIs that support safe parameter handling.
- Prefer parameterized database queries.
- Use ORMs and ODMs correctly.
- Avoid constructing queries through string concatenation.
- Follow the documentation for the libraries and frameworks you use.
- When safe APIs are unavailable, apply appropriate escaping or encoding for the target interpreter.
- 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.
5.1 Recommended Controls
- Limit query depth.
- Limit the number of objects requested.
- Implement pagination.
- Configure reasonable timeouts.
- Enforce query cost limits where appropriate.
- Apply rate limiting per IP address, user, or both.
- Implement server-side batching and caching.
- 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:
- Set maximum limits for collection arguments.
- Enforce pagination.
- Reject requests exceeding the configured limits.
- Apply limits to nested collections as well.
6.3 Implementation Options
For Java:
MaxQueryDepthInstrumentationfrom graphql-java.
For JavaScript:
graphql-depth-limitgraphql-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:
- HTTP servers
- Reverse proxies
- Load balancers
- 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
- Assign costs to expensive fields and operations.
- Account for nested collections.
- Define a maximum allowed query cost.
- Reject queries that exceed the configured limit.
- Test expensive queries in a staging environment before introducing complex cost-analysis logic.
8.3 Implementation Options
For Java:
MaxQueryComplexityInstrumentationfrom graphql-java.
For JavaScript:
graphql-cost-analysisgraphql-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:
- Apply rate limits at the business logic layer.
- Consider query cost when determining request limits.
- Restrict the number of batched operations.
- Apply limits per user or authenticated client.
- 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:
- Combine multiple data-fetching operations.
- Reduce duplicate requests.
- Improve resolver efficiency.
- 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.
11.1 Recommended Controls
- Apply CPU and memory limits.
- Restrict process and file resource usage.
- Configure appropriate database connection limits.
- Monitor resource consumption.
- Use operating system resource controls where appropriate.
- 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
- Validate authorization for every requested object.
- Enforce authorization for both reads and mutations.
- Use RBAC or another appropriate access control mechanism.
- Validate authorization on both edges and nodes.
- Use structured types to expose only permitted properties.
- Implement authorization checks in resolvers or appropriate middleware.
- Disable introspection in production or publicly accessible environments when appropriate.
- 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
- Verify that the requester can access the requested object.
- Apply authorization checks to direct object lookups.
- Protect
nodeandnodesfields where they exist. - Avoid relying on unpredictable identifiers as an authorization mechanism.
- 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
- Identify fields requiring restricted access.
- Validate the requester's permissions before returning sensitive fields.
- Apply authorization checks consistently across resolvers.
- 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
- Restrict mutations to authorized users.
- Verify permissions for the target object.
- Validate which fields the requester can modify.
- Enforce business rules on the server.
- 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
- Application-level Denial of Service.
- Enumeration of users, emails, and object identifiers.
- Brute-force attacks against passwords, OTPs, or session tokens.
- Bypassing request-level rate limits.
- 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.
17.4 Recommended Controls
- Implement application-level object request limits.
- Restrict batching for sensitive operations.
- Limit the number of operations per request.
- Apply query cost and rate limits.
- 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
- Disable excessive error messages.
- Disable stack traces in production responses.
- Disable debug mode in production.
- Disable or restrict introspection.
- Disable or restrict GraphiQL.
- Review schema suggestions and error hints.
- 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
- Disable introspection in production when it is not required.
- Restrict introspection to authenticated or authorized users when necessary.
- Disable GraphiQL in production or publicly accessible environments.
- Avoid exposing internal schema information unnecessarily.
- 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
- Disable stack traces in production responses.
- Disable debug mode.
- Avoid exposing database errors.
- Mask internal errors before returning them to clients.
- Log detailed errors internally for debugging and monitoring.
- 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
nodeandnodesaccess. - 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
- OWASP GraphQL Cheat Sheet
- OWASP Input Validation Cheat Sheet
- OWASP SQL Injection Prevention Cheat Sheet
- OWASP NoSQL Security Cheat Sheet
- graphql-java Documentation
- 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
- cto saleslyt.com academy.saleslyt.com
Comments
Join the discussionNo comments yet. Be the first to comment.





