Skip to main content
Cybersecurity

API Security Best Practices: Rate Limiting, Validation, HTTPS, CORS and OAuth

Mart 29, 2026 5 dk okuma 6 views Raw
Ayrıca mevcut: tr
API security and cybersecurity concept
İçindekiler

Why API Security Is Critically Important

In the modern software ecosystem, APIs (Application Programming Interfaces) form the foundational building blocks of communication between applications. From banking transactions to healthcare data, e-commerce platforms to social media integrations, APIs are used everywhere. This widespread usage makes API security one of the most critical components of cybersecurity.

According to the OWASP API Security Top 10 report, API vulnerabilities cause billions of dollars in data breaches every year. Broken Object Level Authorization (BOLA), Broken Authentication, and Excessive Data Exposure are among the most common API security threats. In this comprehensive guide, we will explore the best practices you need to implement to secure your APIs.

1. Rate Limiting

What Is Rate Limiting?

Rate limiting is a security mechanism that restricts the number of requests a client can make within a specific time window. It serves as the primary defense line against DDoS attacks, brute force attempts, and API abuse.

Rate Limiting Strategies

  • Fixed Window: Applies a fixed limit within defined time periods (e.g., 100 requests per minute).
  • Sliding Window: Uses sliding time windows for more precise control.
  • Token Bucket: Uses a token pool that fills at a specific rate; each request consumes one token.
  • Leaky Bucket: Processes requests at a constant rate, queuing or rejecting excess requests.

Rate Limiting Implementation Recommendations

ParameterRecommended ValueDescription
General API limit1000 requests/minuteFor standard users
Login endpoint5 requests/minuteBrute force protection
Registration endpoint3 requests/hourSpam account prevention
File upload10 requests/hourResource abuse prevention

When implementing rate limiting, it is critical to establish balanced limits that filter malicious traffic without blocking legitimate users. Always send a Retry-After header along with 429 Too Many Requests responses.

2. Input Validation

Why Input Validation Is Essential

Input validation is the most fundamental component of API security. SQL Injection, Cross-Site Scripting (XSS), Command Injection, and XML External Entity (XXE) attacks all originate from insufficient input validation.

Input Validation Principles

  1. Whitelist approach: Define allowed values and reject everything else.
  2. Type checking: Enforce expected data types (string, integer, boolean, etc.).
  3. Length constraints: Set maximum and minimum character lengths.
  4. Regex validation: Use regular expression patterns for fields like email and phone numbers.
  5. Output encoding: Apply HTML, URL, and SQL encoding in output.

API Request Validation Checklist

  • Content-Type header verification
  • Request body size limitation
  • Required field validation
  • Data type and format verification
  • Nested object depth limitation
  • Array size restriction
  • Special character filtering

3. HTTPS and Transport Layer Security

HTTPS Is Mandatory

All API traffic must be conducted over HTTPS. Data sent over HTTP is completely vulnerable to man-in-the-middle (MitM) attacks. TLS 1.2 and above must be used; TLS 1.0 and 1.1 are considered insecure.

HTTPS Best Practices

  • HSTS (HTTP Strict Transport Security): Forces browsers to use only HTTPS connections.
  • Certificate Pinning: Prevents rogue certificate attacks by pre-defining expected certificates.
  • Perfect Forward Secrecy: Uses unique encryption keys for each session.
  • HTTP to HTTPS redirect: Automatically redirect all HTTP requests to HTTPS.

TLS Configuration Comparison

FeatureTLS 1.2TLS 1.3
Handshake time2 RTT1 RTT
0-RTT supportNoYes
Insecure ciphersSome supportedRemoved
PerformanceGoodBetter

4. CORS (Cross-Origin Resource Sharing)

What Is CORS?

CORS is an HTTP mechanism that allows a web application to make API requests from a different origin. When improperly configured, it can lead to serious security vulnerabilities.

CORS Security Rules

  1. Avoid wildcards: Define specific domains instead of using Access-Control-Allow-Origin: *.
  2. Credentials with wildcard: Access-Control-Allow-Credentials: true cannot be used with a wildcard origin.
  3. Preflight requests: Handle OPTIONS requests correctly.
  4. Restrict allowed methods: Only permit necessary HTTP methods.
  5. Header restrictions: Allow only required headers via Access-Control-Allow-Headers.

Leaving CORS configuration loose with a "just make it work" mentality exposes your API to cross-origin attacks. Always start with the most restrictive configuration and relax only as needed.

5. API Keys and Authentication

API Key Security

API keys are the simplest authentication method but do not provide sufficient security on their own. Best practices for API keys include:

  • Send API keys in headers, not URL parameters
  • Rotate keys regularly (every 90 days)
  • Apply the principle of least privilege to each key
  • Disable unused keys
  • Never hardcode keys in source code

OAuth 2.0 and Token Security

OAuth 2.0 is the standard protocol for modern API security. Follow these rules for token-based authentication:

  1. JWT token lifetime: Access tokens should be short-lived (15-30 minutes).
  2. Refresh tokens: Long-lived refresh tokens must be stored securely.
  3. Token revocation mechanism: You must be able to instantly revoke compromised tokens.
  4. Scope limitation: Grant only necessary permissions (scopes) to tokens.
  5. PKCE (Proof Key for Code Exchange): Use PKCE flow for public clients.

6. Additional Security Measures

API Logging and Monitoring

Comprehensive logging and monitoring are essential for detecting security events:

  • Log all authentication failures
  • Detect unusual request patterns
  • Set up real-time alerting mechanisms
  • Store log data in a secure, centralized system

API Versioning and Deprecation

API version management is critical for security:

  • Deprecate old, insecure API versions in a timely manner
  • Define clear policies for version transition periods
  • Inform users with deprecation headers

Conclusion

API security cannot be achieved with a single measure. Rate limiting restricts malicious traffic, input validation prevents injection attacks, HTTPS encrypts data in transit, CORS controls cross-origin access, and OAuth provides strong authentication. When you implement all these layers, you realize the "defense in depth" strategy. API security is an ongoing process; regular security audits, penetration testing, and tracking current threats are indispensable.

Bu yazıyı paylaş