← 中文资源

简体中文版本

How to Secure GraphQL Resolvers

Authorize every GraphQL resolver with field-level checks, depth limiting, and query cost analysis to prevent data leaks and expensive queries.

阅读英文原文

引言

GraphQL gives clients a lot of power: they can ask for any field on any type, nest queries arbitrarily, and request as much data as the schema allows. That power is also a risk. Without authorization on every resolver, a client can read fields they should not see. Without depth and cost limits, a client can craft a query that exhausts the server. This guide shows how to secure resolvers at the field level, limit query depth, and enforce a cost budget. 本文将逐步拆解设计与实现,帮助你在生产环境中安全落地。

问题

A common mistake is to check authorization only at the query entry point. If a user can query a list of users and each user has an email field, the entry-point check passes but the email field is exposed to anyone who can run the query. Another mistake is ignoring query complexity: a nested query like friends-of-friends-of-friends can ask for exponential data and take down the server. 理解问题的全貌是设计正确方案的前提。

设计决策

Authorization belongs in the resolver, not the gateway. Each resolver receives the parent object, arguments, context, and info; the context carries the authenticated user. The resolver checks whether the user can access the field before returning data. For depth, a middleware counts the nesting level and rejects queries deeper than a threshold. For cost, each field has a complexity score; a visitor sums the score and rejects queries over budget. 以下代码展示了核心结构:

const resolvers = {
  User: {
    email: (parent, args, ctx) => {
      if (ctx.user.id !== parent.id && !ctx.user.isAdmin)
        throw new ForbiddenError('cannot read email');
      return parent.email;
    },
  },
};

实现

Install depth limit and cost analysis as middleware or validation rules on the schema. The depth limit rejects queries deeper than a configured max, such as ten levels. The cost analysis walks the query AST, multiplies each field complexity by the number of list items it returns, and rejects queries whose total exceeds the budget. Both run before execution, so expensive queries never hit the resolvers. 实现时需注意性能与正确性的平衡:

import depthLimit from 'graphql-depth-limit';
import costAnalysis from 'graphql-cost-analysis';
const server = new ApolloServer({
  schema,
  validationRules: [
    depthLimit({ maxDepth: 10 }),
    costAnalysis({ maximumCost: 1000, variables: ctx }),
  ],
});

测试边界

Test that a user querying another user’s email gets a ForbiddenError. Test that a query nested twenty levels deep is rejected before execution. Test that a query with a cost of two thousand is rejected, while a cost of five hundred succeeds. Test that an admin can read any email and a normal user can read their own. 测试应覆盖正常路径与异常路径,确保系统在边界条件下行为正确。

常见陷阱

Avoid putting auth only on Query and Mutation types; every field that returns sensitive data needs a check. Avoid setting the cost budget too high; it should reflect the worst-case your server can handle in the request timeout. Avoid skipping depth limits on introspection in production; introspection can be used to map the schema. Avoid logging rejected query details with full context, which may leak the attempted access. 避开这些陷阱可以减少生产事故。

结论

Securing GraphQL resolvers means authorizing every field, limiting depth, and enforcing a cost budget. Put the checks in the resolvers and the limits in validation rules. Test the boundaries: unauthorized access, deep nesting, and expensive queries. The result is a schema that gives clients power without giving them the keys. 按照本文的方法,你可以构建出既安全又高效的解决方案。

Sources: GraphQL security, graphql-cost-analysis.