跳到主要内容
uencoder

如何Build 安全 API Gateway

Design 安全 API 网关该 handles 认证, 速率 limiting, 请求 validation, 和威胁保护为 backend services.

问题

你的 backend services 是 directly exposed 到 clients, making 它们 vulnerable 到 abuse, 未授权 access, 和 malformed requests. 你 need 安全 API 网关 as 单个条目 point 该 enforces 安全 policies 之前 requests reach 你的 services.

前置条件

  • Understanding 的 HTTP APIs 和 REST/GraphQL patterns
  • 熟悉认证 mechanisms (API 关键, JWT, OAuth 2.0)
  • Knowledge 的 OpenAPI/Swagger specifications

步骤

  1. 1. Define the gateway security layers

    Structure the gateway with layered security: (1) TLS termination with modern cipher suites, (2) request size and rate limits, (3) authentication (API key, JWT, OAuth), (4) authorization (scope/role checks), (5) input validation against schema, (6) threat protection (SQL injection, XSS, path traversal), (7) response filtering. Each layer can reject the request before it reaches the backend.

    输入
    incoming HTTP request
    输出
    layers: TLS -> rateLimit -> auth -> authz -> validate -> threats -> backend
  2. 2. Implement authentication and authorization

    Support multiple auth methods: API keys for simple service-to-service, JWT for user sessions, OAuth 2.0 for delegated access. Validate JWT signatures using the issuer's public key, check expiration and audience claims. For API keys, hash-compare against stored hashes (never store plaintext). Enforce scope-based authorization: each endpoint requires specific scopes. Use the JWT parser to inspect tokens and the API spec validator to check endpoints.

    输入
    Authorization: Bearer eyJhbG...
    输出
    auth: valid | user: alice | scopes: [read:data, write:data]
  3. 3. Configure rate limiting and request validation

    Apply tiered rate limits: per-IP, per-user, per-API-key, and global. Use token bucket or sliding window algorithms. Reject requests exceeding limits with HTTP 429 and Retry-After header. Validate every request against the OpenAPI schema: check required fields, types, formats, and value ranges. Reject malformed requests with HTTP 400 before they reach the backend. Use the API spec validator to enforce schema compliance.

    输入
    100 requests/second from one IP
    输出
    HTTP 429 Too Many Requests | Retry-After: 1
  4. 4. Add threat protection and observability

    Filter requests for common attack patterns: SQL injection (malicious quotes, UNION), XSS (script tags, event handlers), path traversal (../), and command injection. Use allow-lists rather than deny-lists where possible. Log all requests with correlation IDs, auth results, response codes, and latency. Monitor for anomalies: spike in 4xx/5xx, unusual request patterns, auth failures. Sanitize all error messages to avoid leaking internal details.

    输入
    query: ' OR 1=1 --
    输出
    blocked: SQL injection pattern | HTTP 400

预期结果

安全 API 网关该 authenticates, authorizes, 速率-limits, validates, 和 protects 所有 backend services 从 abuse 和 attacks, 具有完整 observability.

常见错误

Validating JWT signature but not expiration or audience
Check all claims: signature, exp, nbf, iss, aud, and scope. A valid signature with expired token is still invalid.
Using deny-lists for threat protection
Deny-lists are incomplete and bypassable. Use allow-lists (strict input validation against schema) as the primary defense, with deny-lists as supplementary.
Rate limiting only by IP
IP limits are bypassable via rotation and fail behind shared NAT. Apply per-user and per-API-key limits in addition to per-IP.

排障指引

  • If legitimate users are rate-limited, implement tiered limits (higher for authenticated, lower for anonymous) and allow burst tokens.
  • For GraphQL gateways, add query complexity analysis and depth limiting to prevent resource exhaustion via nested queries.
  • If the gateway becomes a bottleneck, ensure it is stateless (use external Redis for rate limit counters) and horizontally scalable.

安全限制

  • The gateway is a high-value target — compromise of the gateway compromises all services behind it. Secure it with the same rigor as critical services.
  • All token validation and policy enforcement happen at the gateway; backend services should still verify auth independently (defense in depth).
  • Error messages must not leak internal architecture, stack traces, or SQL errors.

相关工具

JWT 解码器
解码并检查 JWT 头部、载荷和时间声明及过期状态。免费、隐私优先、100% 纯客户端运行。本地解析不视为服务端验签。支持 HS256/RS256 等算法头部解析、exp/iat/nbf 时间声明展示,并标注 EXPIRED/NOT YET VALID/VALID 状态。
工具
JWT 编码器
使用 HS256 编码 JWT。免费、隐私优先、100% 纯客户端运行。不用于服务端验签。
工具
OAuth Token 解析器
Oauth Token Parser — 纯客户端工具。隐私优先,无服务器往返。
工具
Bearer Token 生成器
由 token 字符串构造「Bearer <token>」Authorization 头(RFC 6750)。token 会按 b64token 语法校验——字母、数字、-._~+/ 与结尾「=」之外的字符会被拒绝(可防止头部注入)。
工具
API 认证信息提取器
从 OpenAPI 3 规范提取认证方案:输出 components.securitySchemes 的 JSON。不识别 Swagger 2.0 的 securityDefinitions,会返回空对象。
工具
API 规范验证器
检查 OpenAPI/Swagger 规范是否包含必需的顶层字段:openapi/swagger 版本、paths 与 info。不检查字段内容——paths 为非对象值也能通过,因此这只是字段存在性检查,不是结构校验。
工具
API OpenAPI 合并器
合并两个 OpenAPI 规范。
工具
API 错误提取器
从 OpenAPI 提取错误响应。
工具
API 参数提取器
从 OpenAPI 提取参数。
工具
HTTP 状态码参考
常见 HTTP 状态码(1xx-5xx)参考表,包含名称、类别和描述。免费、隐私、100% 客户端运行。
工具
SQL 验证器
轻量 SQL 健全性检查:语句必须以 SQL 关键字开头,且括号必须配平。以括号开头的语句(如 (SELECT 1) UNION (SELECT 2))会被拒绝——这不是真正的 SQL 解析器。
工具
HTML 净化器
基于标签/属性/URI 白名单净化 HTML(移除脚本、事件处理器与不安全 URI)。
工具

相关词条

参考链接