安全 API 设计与速率限制
学习如何通过输入验证、速率限制、安全标头以及针对常见 Web 漏洞的防护,保护 SaaS API 免受滥用和攻击。
安全 API 设计与速率限制 是 CoddyKit 上的免费 SaaS Architecture & Startup Engineering 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 SaaS Architecture & Startup Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 SaaS Architecture & Startup Engineering 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
APIs as the Attack Surface
For a SaaS product, the API is the front door. Every endpoint is a potential entry point for attackers.
Securing APIs goes beyond login: it covers validation, abuse prevention, and protecting against known attack classes.
Validate All Input
Never trust client input. Validate and sanitize every field: type, length, format, and range.
Reject anything unexpected early, before it reaches business logic or the database.
function validateEmail(input) {
const ok = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(input);
if (!ok) throw new Error('Invalid email');
return input.toLowerCase();
}SQL Injection Defense
SQL injection happens when user input is concatenated into queries. The fix is parameterized queries, which separate code from data.
// Unsafe: 'SELECT * FROM users WHERE name = ' + name
// Safe:
db.query('SELECT * FROM users WHERE name = ?', [name]);Rate Limiting Basics
Rate limiting caps how many requests a client can make in a window. It protects against brute-force attacks, scraping, and accidental floods.
Limits are usually per API key, per user, or per IP.
Token Bucket Algorithm
A popular rate-limiting method is the token bucket: tokens refill at a fixed rate, each request consumes one, and requests are denied when the bucket is empty.
let tokens = 10;
function allow() {
if (tokens > 0) { tokens--; return true; }
return false;
}
// refill periodically: tokens = Math.min(10, tokens + 1)Returning 429
When a client exceeds the limit, return HTTP status 429 Too Many Requests with a Retry-After header telling them when to try again.
Clear feedback lets well-behaved clients back off gracefully.
Secure HTTP Headers
Add defensive headers to every response:
- Strict-Transport-Security forces HTTPS
- X-Content-Type-Options: nosniff
- Content-Security-Policy limits script sources
CORS Configuration
CORS controls which web origins may call your API from a browser. Set an explicit allowlist of trusted origins.
Never use a wildcard with credentials enabled, as it exposes your API to any site.
Avoiding Excessive Data Exposure
APIs often return entire database objects, leaking internal fields. Always return an explicit response shape with only the fields the client needs.
Never send password hashes, internal IDs, or audit fields to the client.
function publicUser(u) {
return { id: u.id, name: u.name, email: u.email };
// omit password_hash, internal flags
}Idempotency and Replay Protection
Network retries can cause duplicate operations. Support idempotency keys so retrying a payment or write produces the same result once.
This protects both correctness and security against replay attacks.
Logging and Monitoring Abuse
Security is not only prevention. Log authentication failures, rate-limit hits, and suspicious patterns. Alert when an account shows signs of attack.
Visibility lets you respond before a breach becomes a disaster.
Quick Check
Test your API security knowledge.
Recap
You learned to harden SaaS APIs:
- Validate input and use parameterized queries
- Rate limit with token buckets and return 429
- Add secure headers, strict CORS, minimal response shapes, and idempotency
- Log and monitor abuse
常见问题解答
「安全 API 设计与速率限制」课时是免费的吗?
是的 — 「安全 API 设计与速率限制」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 SaaS Architecture & Startup Engineering 课程的其余内容,请升级到 CoddyKit PRO。 SaaS Architecture & Startup Engineering 课程共包含 4 节课。
「安全 API 设计与速率限制」这节课中我会学到什么?
学习如何通过输入验证、速率限制、安全标头以及针对常见 Web 漏洞的防护,保护 SaaS API 免受滥用和攻击。 你通过在浏览器中直接运行的动手代码来练习 SaaS Architecture & Startup Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 SaaS Architecture & Startup Engineering 需要有经验吗?
无需任何先前经验。CoddyKit 上的 SaaS Architecture & Startup Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「安全 API 设计与速率限制」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 SaaS Architecture & Startup Engineering 课中编写并运行代码吗?
能。每节 SaaS Architecture & Startup Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。