Back to blog

How Companies Can Secure Their APIs: Practical Steps

Published April 7, 2026

This guide explains how to build a practical and repeatable API security model: from inventory and authentication to testing, monitoring, and incident response.

1) Inventory and Basic Hygiene

  • Complete API inventory. Production, staging, internal, and experimental APIs. Map every endpoint to its owning team.
  • Contracts. Store OpenAPI/AsyncAPI schemas in the repository. Enable schema validation in CI.
  • Lifecycle. Specify the status (alpha/beta/GA/deprecated) and EOL date. Use versioning: /v1, /v2.

2) Strong Authentication and Authorization

  • OAuth2/OIDC + JWT for public and mobile clients; mTLS or signed keys for service-to-service communication.
  • Scopes/permissions. Follow the principle of least privilege and use separate tokens for each use case.
  • Rotation and a short TTL. Use short-lived access tokens and rotate refresh tokens.
  • BOLA/BFLA protection. Verify access rights for every resource, not only the user’s role.
Example (OpenAPI securitySchemes)
{
  "components": {
    "securitySchemes": {
      "oauth2": {
        "type": "oauth2",
        "flows": {
          "authorizationCode": {
            "authorizationUrl": "https://auth.example.com/oauth/authorize",
            "tokenUrl": "https://auth.example.com/oauth/token",
            "scopes": {
              "orders:read": "Read orders",
              "orders:write": "Create/modify orders"
            }
          }
        }
      }
    }
  },
  "security": [{ "oauth2": ["orders:read"] }]
}

3) Transport Security and Headers

  • TLS 1.2+ is mandatory, with HSTS enabled and HTTP disabled. Use mTLS for internal services.
  • CORS: allow only trusted origins and keep credentials off by default.
  • Security headers: Content-Security-Policy, X-Content-Type-Options: nosniff, Referrer-Policy.

4) Input Validation and Injection Protection

  • Schemas: apply JSON Schema/DTO validation before business logic.
  • Field constraints: maximum length, allowed enums, and strict types; reject unexpected fields to prevent mass assignment.
  • Sanitization for HTML/SQL/LDAP/NoSQL. Use parameterized queries.

5) Limits, Quotas, and Abuse Prevention

  • Rate limiting (per IP, per token, and per user) and burst control.
  • Quotas per day or month, with separate limits for background jobs and interactive clients.
  • Pagination + server-side filtering to prevent bulk data extraction (scraping).
Example (nginx rate limit)
limit_req_zone $binary_remote_addr zone=api_zone:10m rate=10r/s;
server {
  location /api/ {
    limit_req zone=api_zone burst=30 nodelay;
  }
}

6) Secrets and Keys

  • Vault/KMS, with no secrets stored in Git or unencrypted environment variables.
  • Bind keys to specific environments, rotate them regularly, and maintain detailed audit logs.

7) Logging, Monitoring, and Threat Detection

  • Standardized logs: request id, subject (userId/clientId), scope, resource, result, and latency.
  • Anomalies: sudden spikes in 401/403/429 responses, unusual locations, or unexpected scopes should trigger alerts and SIEM events.
  • Idempotency for POST requests (an idempotency key) + client-side retries.

8) Webhooks

  • Message signing (HMAC) + timestamp, with time-skew validation.
  • Retries with backoff, idempotent handlers, and an IP allowlist or mTLS.
Signature verification example (PHP)
<?php
$payload = file_get_contents('php://input');
$ts = $_SERVER['HTTP_X_TS'] ?? '';
$sig = $_SERVER['HTTP_X_SIG'] ?? '';
$secret = getenv('WEBHOOK_SECRET');

$base = $ts . '.' . $payload;
$calc = base64_encode(hash_hmac('sha256', $base, $secret, true));

if (!hash_equals($calc, $sig) || abs(time() - (int)$ts) > 300) {
  http_response_code(401);
  exit('invalid signature');
}
echo 'ok';

9) Continuous Security Testing

  • SAST/DAST in CI, with fuzzing based on the OpenAPI contract.
  • Contract testing between provider ↔ consumer (Pact, etc.).
  • OWASP API Top 10 checks (BOLA, BFLA, Excessive Data Exposure, Mass Assignment, SSRF, etc.).
  • Bug bounty programs or private researchers before and after releasing major changes.

10) Incident Response Processes

  • A runbook for key leaks, compromised tokens, and large-scale brute-force attacks.
  • A “kill switch” for revoking keys and tokens, blocking locations or clients, and lowering limits.
  • A client communication plan and procedures for meeting regulatory obligations.

Quick Pre-Release Checklist

  • ✅ OpenAPI schema updated and validated in CI
  • ✅ OAuth2/OIDC or mTLS, short-lived tokens, and rotation
  • ✅ Resource-level authorization checks (BOLA)
  • ✅ Input validation and rejection of unexpected fields
  • ✅ Rate limiting + quotas, with CORS restricted to trusted origins
  • ✅ Secrets stored in Vault/KMS and keys rotated
  • ✅ Logs include request id, with alerts configured for anomalies
  • ✅ Webhooks are signed and idempotent
  • ✅ SAST/DAST/fuzzing in CI, with OWASP API Top 10 checks
  • ✅ Incident runbook and “kill switch” tested

API security is not a one-time audit but an ongoing discipline. Start with the essential controls, automate checks in CI/CD, and maintain transparency: clear contracts, useful logs, and accountable service owners.