Guide

API Security Best Practices for SaaS Products

Quick answer

Securing your API requires multiple layers: use OAuth 2.0 with short-lived tokens, enforce rate limiting per user (e.g., 1000 req/hour), validate all input, use HTTPS, and log suspicious activity. For critical endpoints, implement role-based access control (RBAC) and never trust client-side IDs.

Use Strong Authentication and Authorization

Start with OAuth 2.0 for authentication. Issue short-lived access tokens (15 minutes) and longer refresh tokens (7 days). Store tokens securely, never in local storage. Use HTTPS-only cookies for web apps.

For authorization, implement RBAC. Map each API route to a required role. Example: POST /api/admin/users requires admin role. Verify roles on every request, not just at login.

Never trust user-supplied IDs. Always check that the authenticated user owns the resource. For example, GET /api/users/123/orders should only return orders belonging to user 123, not any user.

Validate All Input

Assume all input is malicious. Validate on the server side, never rely on client-side checks alone.

  • Whitelist allowed values for enums, IDs, and file types.
  • Sanitize strings to prevent XSS and injection attacks. Use parameterized queries for databases.
  • Reject unexpected fields in JSON payloads. Use strict schemas (e.g., JSON Schema validation).

Example: For an email input, reject anything that doesn't match ^[\w.-]+@[\w.-]+\.\w+$. For numeric IDs, reject non-integer values.

Rate Limit and Throttle Requests

Rate limiting prevents abuse and brute-force attacks. Set limits per user, per IP, and per endpoint.

Common limits: 1000 requests per hour for standard users, 100 per minute for login endpoints. Return 429 Too Many Requests with a Retry-After header.

Use a sliding window algorithm for accuracy. Example in Node.js with express-rate-limit:

const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
 windowMs: 60 * 60 * 1000,
 max: 1000,
 message: 'Too many requests'
});
app.use('/api/', limiter);

Enforce HTTPS and Secure Headers

Use HTTPS for all API traffic. Redirect HTTP to HTTPS. Set the Strict-Transport-Security header with a max-age of one year (31536000 seconds) to force HTTPS.

Add security headers to responses:

  • Content-Security-Policy: restrict sources for scripts, styles, and images.
  • X-Content-Type-Options: nosniff to prevent MIME sniffing.
  • X-Frame-Options: DENY to prevent clickjacking.
  • Cache-Control: no-store for sensitive endpoints.

Log and Monitor API Activity

Log every API request and response, including timestamps, IPs, user IDs, and endpoints. Store logs in a central system like AWS CloudWatch or ELK stack.

Set up alerts for suspicious patterns: multiple failed logins, requests to admin endpoints from non-admin users, spikes in 4xx errors, or unusual payload sizes.

Review logs regularly. Automated tools can detect anomalies. For example, 10 failed login attempts from the same IP in 5 minutes should trigger an alert and temporary block.

Secure Your Secrets and Dependencies

Never hardcode API keys, database passwords, or tokens in code. Use environment variables or a secrets manager like AWS Secrets Manager.

Rotate secrets regularly. For example, rotate API keys every 90 days. Use short-lived credentials for database access.

Keep dependencies up to date. Use automated scanning tools (e.g., Snyk, Dependabot) to find vulnerable libraries. Apply patches quickly, especially for critical vulnerabilities.

Test Your API Security Regularly

Automated testing catches common vulnerabilities. Use tools to scan for OWASP Top 10 issues like broken access control, injection, and misconfiguration.

For deeper testing, consider penetration testing. Tools like Kyro can continuously test your API for vulnerabilities. Start a free scan to see how your API holds up.

Manual code reviews and threat modeling also help. Review API design for flaws like missing authentication on endpoints or excessive data exposure.

Find these bugs in your own app

Kyro runs an AI security hunter against your SaaS and emails you the moment it confirms a real, reproducible vulnerability.

Start a free scan

Frequently asked questions

What is the most important API security best practice?

Authentication and authorization are the most critical. Without strong access controls, other measures are ineffective. Use OAuth 2.0 with short-lived tokens and enforce RBAC on every endpoint.

How do I protect my API from DDoS attacks?

Rate limiting and throttling help, but for large attacks use a CDN or DDoS protection service like Cloudflare or AWS Shield. Also set request size limits and timeouts.

Should I validate input on the client or server?

Always validate on the server. Client-side validation is for UX only. Attackers can bypass client checks. Server-side validation is your only trustworthy defense.

How often should I rotate API keys?

Rotate API keys every 90 days as a baseline. For high-risk environments, rotate every 30 days. Use a secrets manager to automate rotation and avoid downtime.