Why API Security Matters

APIs (Application Programming Interfaces) are the backbone of modern applications. They connect mobile apps to backends, link microservices together, and expose data to third-party integrations. Because APIs handle sensitive data and business logic, they are prime targets for attackers.

Unlike traditional web applications where a browser enforces some security controls, APIs are often accessed programmatically. This means attackers can easily automate requests, manipulate parameters, and bypass client-side checks.

💡
OWASP API Security Top 10

OWASP maintains a dedicated API Security Top 10 list, separate from the web application Top 10. The most critical API vulnerabilities include broken object-level authorization, broken authentication, and excessive data exposure.

Authentication Methods

Every API must verify the identity of its callers. There are several authentication mechanisms, each with different security profiles and use cases.

API Keys

API keys are simple tokens passed in headers or query parameters. They identify the calling application but not the user. API keys alone are not sufficient for user-level authentication.

# API key in header (preferred)
curl -H "X-API-Key: your-api-key-here" https://api.example.com/data

# API key in query parameter (less secure - logged in URLs)
curl https://api.example.com/data?api_key=your-api-key-here

OAuth 2.0 and JWT

OAuth 2.0 is the industry standard for delegated authorization. It issues access tokens (often as JWTs) that carry claims about the user and their permissions. JWTs are cryptographically signed, allowing the API to verify them without contacting the auth server on every request.

# Bearer token authentication
curl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..." \
     https://api.example.com/user/profile
⚠️
Never trust client-supplied JWTs blindly

Always verify the signature, check the expiration (exp claim), validate the issuer (iss), and confirm the audience (aud). Accepting unsigned tokens or tokens with alg: none is a critical vulnerability.

Rate Limiting and Throttling

Without rate limiting, attackers can abuse your API through brute force attacks, data scraping, or denial of service. Rate limiting controls how many requests a client can make within a time window.

Common Strategies

  • Fixed Window - Allow N requests per time window (e.g., 100 requests per minute)
  • Sliding Window - Smoother rate limiting that avoids burst traffic at window boundaries
  • Token Bucket - Allows short bursts while maintaining an average rate
  • Per-Endpoint Limits - Different limits for different endpoints based on cost and sensitivity

Response Headers

Communicate rate limit status to clients through standard headers:

HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 47
X-RateLimit-Reset: 1709424000

# When limit is exceeded:
HTTP/1.1 429 Too Many Requests
Retry-After: 30

Input Validation for APIs

APIs must validate every piece of incoming data. Unlike web forms, API consumers can send any JSON structure, any content type, and any parameter values. Never trust client input.

Schema Validation

Use a schema definition (like JSON Schema or OpenAPI) to validate the structure and types of request bodies before processing them.

// Example JSON Schema for a user creation endpoint
{
  "type": "object",
  "required": ["email", "name"],
  "properties": {
    "email": {
      "type": "string",
      "format": "email",
      "maxLength": 254
    },
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 100
    },
    "role": {
      "type": "string",
      "enum": ["user", "editor"]
    }
  },
  "additionalProperties": false
}
⚠️
Watch for mass assignment

If your API automatically maps request fields to database columns, an attacker could add fields like "role": "admin" or "is_verified": true. Always use an allowlist of accepted fields and reject unknown properties.

CORS Configuration

Cross-Origin Resource Sharing (CORS) controls which domains can call your API from a browser. Misconfigured CORS is one of the most common API security issues.

Secure CORS Setup

# Good: Specific allowed origins
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 86400

# Bad: Wildcard allows any website to call your API
Access-Control-Allow-Origin: *
  • Never use wildcard origins with credentialed requests
  • Never reflect the Origin header directly into Access-Control-Allow-Origin without validation
  • Limit allowed methods to only what each endpoint needs
  • Set a reasonable max-age for preflight caching

Error Handling and Data Exposure

API error responses can leak sensitive information if not handled carefully. Stack traces, database error messages, and internal paths should never reach the client.

Good vs Bad Error Responses

// BAD: Leaks internal details
{
  "error": "SQL Error: SELECT * FROM users WHERE id = '1 OR 1=1'",
  "stack": "at Database.query (db.js:45)\n    at UserController..."
}

// GOOD: Generic message with reference ID
{
  "error": "An internal error occurred",
  "code": "INTERNAL_ERROR",
  "reference": "err-2026-03-abc123"
}

Log detailed errors server-side with the reference ID so you can investigate without exposing details to attackers.

Monitoring and Logging

You cannot secure what you cannot see. API monitoring detects attacks in progress and helps with forensic analysis after incidents.

What to Log

  • Authentication events - Failed logins, token refresh, privilege changes
  • Authorization failures - Attempts to access unauthorized resources
  • Rate limit violations - IPs or users hitting rate limits repeatedly
  • Input validation failures - Malformed requests may indicate attack attempts
  • Unusual patterns - Sudden spikes in traffic, unusual endpoints being accessed
💡
Never log sensitive data

Exclude passwords, API keys, tokens, credit card numbers, and personal data from logs. If you must log request bodies, sanitize sensitive fields first.

Summary

In this tutorial, you learned:

  • Why APIs are high-value targets and need dedicated security measures
  • How to choose and implement authentication (API keys, OAuth, JWT)
  • Rate limiting strategies to prevent abuse and denial of service
  • Input validation with schema definitions to reject malformed requests
  • Proper CORS configuration to control cross-origin access
  • Secure error handling that avoids leaking internal details
  • What to monitor and log for attack detection
🎉
Your APIs are fortified!

By applying these fundamentals consistently, you build APIs that are resilient against the most common attack vectors. Remember: defense in depth means applying multiple layers of security, not relying on any single control.