api-security
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Security Development Guide
API安全开发指南
Structured approach to building secure APIs, covering OWASP API Security Top 10 (2023), secure design patterns, and verification checklists. Apply these guidelines throughout the API development lifecycle — from threat modeling to deployment monitoring.
构建安全API的结构化方法,涵盖OWASP API安全Top 10(2023)、安全设计模式及验证检查清单。在API开发生命周期的各个阶段——从威胁建模到部署监控——均需遵循这些指南。
Secure API Development Lifecycle
安全API开发生命周期
Phase 1: API Threat Modeling and Design
阶段1:API威胁建模与设计
- Identify API attack surfaces: public endpoints, authenticated endpoints, admin endpoints, webhooks, third-party integrations
- Map data flows: what sensitive data crosses each API boundary
- Define authorization model: which users/roles access which resources and properties
- Design security controls:
- Centralized authentication (OAuth2/OIDC at API gateway)
- Object-level authorization at data access layer
- Schema-based input validation at every endpoint
- Rate limiting per endpoint sensitivity
- API versioning with deprecation strategy
- 识别API攻击面:公开端点、已认证端点、管理员端点、Webhook、第三方集成
- 映射数据流:哪些敏感数据会跨越各API边界
- 定义授权模型:哪些用户/角色可访问哪些资源及属性
- 设计安全控制:
- 集中式身份认证(API网关处采用OAuth2/OIDC)
- 数据访问层的对象级授权
- 每个端点基于Schema的输入验证
- 按端点敏感度设置速率限制
- 带有弃用策略的API版本管理
Phase 2: Secure Implementation
阶段2:安全实现
Critical API Security Rules
关键API安全规则
| Never | Instead |
|---|---|
| Return full objects (to_dict/to_json) | Explicit response schemas with cherry-picked fields |
| Accept arbitrary fields for update | Allowlisted update schemas (prevent mass assignment) |
| Use sequential/guessable IDs in URLs | UUIDs/GUIDs for resource identifiers |
| Trust object ID alone for access | Check object ownership against authenticated user |
| Rely on client-side role checks | Server-side RBAC/ABAC middleware |
| Accept unlimited query params/body | Schema validation with size/type/range limits |
| Skip rate limiting on any endpoint | Rate limit ALL endpoints, stricter on auth/business flows |
| Return stack traces in errors | RFC 7807 Problem Details with generic messages |
| Trust third-party API responses | Validate and sanitize all external API data |
| Put API keys in URLs | Use Authorization header or secure key vault |
| Use wildcard CORS with credentials | Explicit origin allowlist |
| Allow unlimited GraphQL depth/complexity | Query depth + complexity + batch limits |
Reference detailed guides:
- For OWASP API Top 10 with code examples: See references/owasp-api-top-10.md
- For secure API design patterns: See references/secure-api-design.md
| 禁止操作 | 替代方案 |
|---|---|
| 返回完整对象(to_dict/to_json) | 使用明确的响应Schema,仅返回指定字段 |
| 接受任意字段用于更新 | 使用允许列表式的更新Schema(防止批量赋值) |
| 在URL中使用连续/可猜测的ID | 采用UUID/GUID作为资源标识符 |
| 仅依赖对象ID进行访问控制 | 验证对象归属与已认证用户是否匹配 |
| 依赖客户端角色校验 | 使用服务端RBAC/ABAC中间件 |
| 接受无限制的查询参数/请求体 | 进行Schema验证,设置大小/类型/范围限制 |
| 不对任何端点设置速率限制 | 对所有端点设置速率限制,认证/业务流端点限制更严格 |
| 错误响应中返回堆栈跟踪 | 使用RFC 7807问题详情格式,返回通用消息 |
| 信任第三方API响应 | 验证并清理所有外部API数据 |
| 将API密钥放入URL | 使用Authorization头或安全密钥管理库 |
| 凭证与通配符CORS一起使用 | 使用明确的源允许列表 |
| 允许无限制的GraphQL深度/复杂度 | 设置查询深度+复杂度+批量限制 |
参考详细指南:
- 包含代码示例的OWASP API Top 10指南:参见references/owasp-api-top-10.md
- 安全API设计模式:参见references/secure-api-design.md
Phase 3: API Security Verification
阶段3:API安全验证
- Schema Validation — Lint OpenAPI spec for security issues (Spectral)
- Static Analysis — Run SAST on API code (Semgrep, bandit)
- Contract Testing — Verify API behavior matches spec (Schemathesis, Dredd)
- Dynamic Testing — Run DAST against running API (OWASP ZAP, Burp Suite)
- Authorization Testing — Test every endpoint with wrong user/role/anonymous
- Rate Limit Testing — Verify all endpoints enforce limits
- Code Review — Apply API security checklists
Reference: See references/api-security-checklist.md
- Schema验证 — 检查OpenAPI规范中的安全问题(Spectral)
- 静态分析 — 对API代码运行SAST扫描(Semgrep、bandit)
- 契约测试 — 验证API行为是否符合规范(Schemathesis、Dredd)
- 动态测试 — 对运行中的API进行DAST扫描(OWASP ZAP、Burp Suite)
- 授权测试 — 使用错误用户/角色/匿名身份测试每个端点
- 速率限制测试 — 验证所有端点均执行限制规则
- 代码审查 — 应用API安全检查清单
参考:参见references/api-security-checklist.md
Phase 4: Deployment and Monitoring
阶段4:部署与监控
- API gateway: auth offloading, rate limiting, request logging
- TLS 1.2+ enforcement, HSTS, security headers
- Structured logging (no tokens/PII in logs)
- Anomaly detection and alerting on security events
- API inventory management and version deprecation
- Incident response plan for API breaches
- API网关:身份认证卸载、速率限制、请求日志
- 强制使用TLS 1.2+、HSTS、安全头
- 结构化日志(日志中不包含令牌/PII)
- 安全事件的异常检测与告警
- API库存管理与版本弃用
- API泄露事件响应计划
OWASP API Security Top 10 (2023) Quick Reference
OWASP API安全Top 10(2023)速查
| # | Risk | Key Concern | Primary Prevention |
|---|---|---|---|
| API1 | Broken Object Level Authorization | Accessing other users' resources by manipulating IDs | Object ownership check at data layer, use GUIDs |
| API2 | Broken Authentication | Weak auth, credential stuffing, JWT flaws | OAuth2/OIDC, short-lived tokens, rate limit auth |
| API3 | Broken Object Property Level Authorization | Excessive data exposure + mass assignment | Explicit response/request schemas, field allowlists |
| API4 | Unrestricted Resource Consumption | No rate/size/cost limits, GraphQL batching | Rate limiting, pagination caps, spending alerts |
| API5 | Broken Function Level Authorization | Regular users accessing admin functions | RBAC middleware, deny by default, test all roles |
| API6 | Unrestricted Access to Sensitive Business Flows | Automating business-critical operations (scalping, spam) | CAPTCHA, device fingerprinting, behavior analysis |
| API7 | Server Side Request Forgery | API fetches user-supplied URLs | URL allowlisting, block private IPs, disable redirects |
| API8 | Security Misconfiguration | Missing headers, CORS *, verbose errors, debug endpoints | Hardened defaults, security headers, minimal errors |
| API9 | Improper Inventory Management | Shadow APIs, deprecated versions, no documentation | API inventory, OpenAPI in CI/CD, retirement plans |
| API10 | Unsafe Consumption of APIs | Trusting third-party API data without validation | Validate all external data, enforce TLS, set timeouts |
For detailed attack scenarios and code examples: See references/owasp-api-top-10.md
| # | 风险 | 核心问题 | 主要预防措施 |
|---|---|---|---|
| API1 | 对象级授权失效 | 通过操纵ID访问其他用户的资源 | 在数据层检查对象归属,使用GUID |
| API2 | 身份认证失效 | 弱认证、凭证填充、JWT漏洞 | OAuth2/OIDC、短生命周期令牌、认证速率限制 |
| API3 | 对象属性级授权失效 | 过度数据暴露+批量赋值 | 明确的响应/请求Schema、字段允许列表 |
| API4 | 资源消耗无限制 | 无速率/大小/成本限制、GraphQL批量请求 | 速率限制、分页上限、支出告警 |
| API5 | 功能级授权失效 | 普通用户访问管理员功能 | RBAC中间件、默认拒绝、测试所有角色 |
| API6 | 敏感业务流访问无限制 | 自动化执行关键业务操作(刷单、垃圾信息) | CAPTCHA、设备指纹、行为分析 |
| API7 | 服务器端请求伪造(SSRF) | API获取用户提供的URL | URL允许列表、阻止私有IP、禁用重定向 |
| API8 | 安全配置错误 | 缺失头信息、CORS通配符、详细错误信息、调试端点 | 强化默认配置、安全头、简化错误信息 |
| API9 | 库存管理不当 | 影子API、已弃用版本、无文档 | API库存、CI/CD中集成OpenAPI、版本退役计划 |
| API10 | API使用不安全 | 未经验证就信任第三方API数据 | 验证所有外部数据、强制使用TLS、设置超时 |
详细攻击场景与代码示例:参见references/owasp-api-top-10.md
API Security Review Workflow
API安全审查工作流
Step-by-step procedure for reviewing API security:
- Map the API surface — List all endpoints, methods, auth requirements, and data flows. Check for undocumented/shadow endpoints.
- Check authentication — Verify every non-public endpoint requires valid authentication. Test with missing/expired/malformed tokens.
- Check object-level authorization (BOLA) — For every endpoint accepting resource IDs, verify users can only access their own resources.
- Check function-level authorization (BFLA) — Verify admin endpoints reject non-admin users. Test horizontal and vertical privilege escalation.
- Check property-level authorization — Verify responses only include authorized fields. Test mass assignment by sending extra fields in updates.
- Validate input handling — Check schema validation on all inputs. Test with oversized payloads, unexpected types, injection payloads.
- Check rate limiting — Verify limits on all endpoints, especially auth, business-critical, and resource-intensive operations.
- Check error handling — Verify no sensitive info in error responses. Test with invalid inputs, missing resources, server errors.
- Review third-party integrations — Verify external API responses are validated. Check for SSRF in URL-accepting endpoints.
- Check API inventory — Verify no deprecated/shadow endpoints are live. Check documentation matches reality.
- Report findings — Severity (Critical/High/Medium/Low), endpoint, vulnerable request, explanation, fix with code example.
API安全审查的分步流程:
- 映射API攻击面 — 列出所有端点、方法、认证要求及数据流。检查是否存在未文档化/影子端点。
- 检查身份认证 — 验证所有非公开端点均要求有效身份认证。使用缺失/过期/格式错误的令牌进行测试。
- 检查对象级授权(BOLA) — 对每个接受资源ID的端点,验证用户仅能访问自己的资源。
- 检查功能级授权(BFLA) — 验证管理员端点拒绝非管理员用户访问。测试横向与纵向权限提升。
- 检查属性级授权 — 验证响应仅包含授权字段。通过在更新请求中发送额外字段测试批量赋值漏洞。
- 验证输入处理 — 检查所有输入的Schema验证。使用超大载荷、意外类型、注入载荷进行测试。
- 检查速率限制 — 验证所有端点均设置限制,尤其是认证、关键业务及资源密集型操作的端点。
- 检查错误处理 — 验证错误响应中无敏感信息。使用无效输入、缺失资源、服务器错误进行测试。
- 审查第三方集成 — 验证外部API响应已被验证。检查接受URL的端点是否存在SSRF漏洞。
- 检查API库存 — 验证无已弃用/影子端点处于活跃状态。检查文档与实际情况是否一致。
- 报告发现 — 包含严重程度(Critical/High/Medium/Low)、端点、漏洞请求、说明、带代码示例的修复方案。
API Security Testing Quick Commands
API安全测试快速命令
bash
undefinedbash
undefined=== OpenAPI Spec Linting ===
=== OpenAPI Spec Linting ===
npm install -g @stoplight/spectral-cli && spectral lint openapi.yaml
npm install -g @stoplight/spectral-cli && spectral lint openapi.yaml
=== Property-based API Testing ===
=== Property-based API Testing ===
pip install schemathesis && schemathesis run --checks all http://localhost:8000/openapi.json
pip install schemathesis && schemathesis run --checks all http://localhost:8000/openapi.json
=== Dynamic Security Scanning ===
=== Dynamic Security Scanning ===
docker run -t ghcr.io/zaproxy/zaproxy:stable zap-api-scan.py -t http://target:8000/openapi.json -f openapi
docker run -t ghcr.io/zaproxy/zaproxy:stable zap-api-scan.py -t http://target:8000/openapi.json -f openapi
=== API Fuzzing ===
=== API Fuzzing ===
nuclei -u http://target:8000 -t api/
nuclei -u http://target:8000 -t api/
=== Static Analysis (Python API) ===
=== Static Analysis (Python API) ===
pip install bandit && bandit -r src/ -f json
pip install semgrep && semgrep --config=p/python --config=p/owasp-top-ten src/
undefinedpip install bandit && bandit -r src/ -f json
pip install semgrep && semgrep --config=p/python --config=p/owasp-top-ten src/
undefinedReference Files
参考文件
- references/owasp-api-top-10.md — Detailed OWASP API Security Top 10 (2023) with attack scenarios, vulnerable → secure code examples for REST and GraphQL APIs
- references/secure-api-design.md — Secure API design patterns: authentication (OAuth2, JWT, API keys, mTLS), authorization (RBAC/ABAC), input validation, rate limiting, CORS, error handling, API gateway, monitoring
- references/api-security-checklist.md — Actionable checklists for API design review, auth, input validation, transport security, rate limiting, inventory, deployment, logging, and testing
- references/owasp-api-top-10.md — 详细的OWASP API安全Top 10(2023),包含攻击场景、REST和GraphQL API的漏洞代码→安全代码示例
- references/secure-api-design.md — 安全API设计模式:身份认证(OAuth2、JWT、API密钥、mTLS)、授权(RBAC/ABAC)、输入验证、速率限制、CORS、错误处理、API网关、监控
- references/api-security-checklist.md — 可执行的检查清单,涵盖API设计审查、认证、输入验证、传输安全、速率限制、库存、部署、日志及测试