Skip to content
IRC-CodingIRC-Coding
API Gateway SecurityRate LimitingWAFmTLSOAuthJWTKongThreat ProtectionAPI Hardening

API Gateway Security: Authentication, Rate Limiting & Best Practices

Master API Gateway security with OAuth, JWT, rate limiting, WAF, mTLS, IP whitelisting, and audit logging.

S

schutzgeist

13 min read
API Gateway Security: Authentication, Rate Limiting & Best Practices

API Gateway Security: Authentication, Threat Protection, and Hardening

The API Gateway is the single entry point for all API traffic. If it’s insecure, everything behind it is exposed. If it’s properly configured, it protects your entire infrastructure—from authentication checks to bot defense.

What is API Gateway Security?

API Gateway security encompasses all measures that protect the gateway itself and the APIs flowing through it from attacks, abuse, and misconfiguration. Because the gateway is the only entry point for external traffic, it’s the ideal place to enforce security policies centrally.

API Gateway security typically breaks down into four areas:

  1. Access Control: Who can call the API? (Authentication and authorization)
  2. Traffic Control: How much can a client request? (Rate limiting, quotas, throttling)
  3. Threat Protection: Which attacks get blocked? (WAF, bot protection, schema validation)
  4. Hardening: How is the gateway itself protected? (mTLS, IP whitelisting, admin API security, audit logs)

Who uses API Gateway security?

  • Platform teams set central security policies across all APIs
  • Security engineers define threat protection rules and monitor attacks
  • API teams specify authentication requirements per endpoint
  • DevOps engineers harden the gateway infrastructure (TLS, admin access, secrets management)

Why this matters in computer science and professional exams

API Gateway security is core material in cloud certifications (AWS Certified Security, Azure Security Engineer) and the OWASP API Security Top 10. Professional exams frequently ask about centralized versus decentralized authentication. Centralizing security at the gateway reduces complexity and single points of failure—but only if you properly protect the gateway itself from becoming a bottleneck or vulnerability.

Core Concepts

1. Centralized Authentication at the Gateway

The gateway handles authentication for all APIs. The client sends a token (JWT, API key, or OAuth access token) to the gateway. The gateway validates the token signature, extracts the claims, and forwards the request to the backend with enriched headers.

The flow:

  1. Client sends Authorization: Bearer <token>
  2. Gateway validates token signature and expiration
  3. Gateway extracts claims (user ID, roles, scopes)
  4. Gateway forwards the request with headers like X-User-Id, X-Roles
  5. Backend trusts these headers (since they come from the gateway) and enforces authorization logic

Critical: the internal network between gateway and backend must be trusted. Headers must not be manipulable from outside. Cloud deployments achieve this through VPC isolation or mTLS.

OAuth 2.0 Integration

The gateway can act as an OAuth Resource Server, validating access tokens against an authorization server via introspection or JWKS verification. You define required scopes per endpoint:

  • /api/ordersorders:read scope for GET, orders:write for POST
  • /api/admin/usersadmin:users scope

API Key Management

For B2B clients without OAuth infrastructure, the gateway manages API keys. Each key belongs to a consumer and grants specific permissions. The gateway can rotate keys, revoke them, and assign quotas.

2. Rate Limiting and Quotas

Rate limiting at the gateway is the first line of defense against abuse. It’s more granular than reverse-proxy rate limiting:

  • Per consumer: Each API key has its own limit
  • Per endpoint: Critical endpoints have lower limits
  • Per combination: A consumer might have 100 req/min globally but only 10 req/min on /api/export
  • Tiered: Free tier 100 req/h, Pro tier 1000 req/min, Enterprise unlimited

Common algorithms:

  • Fixed window: Counts requests in time buckets (e.g., 100 per minute). Simple but allows bursts at window boundaries.
  • Sliding window: Smoother distribution over a moving time window.
  • Token bucket: A bucket fills with tokens over time; each request consumes one token. Allows bursts until the bucket empties.

Exceeded limits return 429 Too Many Requests with a Retry-After header.

3. Web Application Firewall (WAF) at the Gateway

A WAF at the gateway filters malicious requests before they reach the backend:

  • SQL Injection: Blocks patterns like ' OR 1=1 -- in query parameters
  • XSS: Detects and blocks <script> tags in input
  • Path Traversal: Blocks ../../etc/passwd in URL paths
  • Command Injection: Detects ; rm -rf / in parameters
  • Anomaly Detection: Flags unusual request sizes, header combinations

WAF rules can be positive (whitelist: only known good requests) or negative (blacklist: block known attacks). Best practice combines both: whitelist for sensitive endpoints, blacklist for general traffic.

4. Schema Validation

The gateway validates every request against an OpenAPI schema:

  • Are all required fields present?
  • Are data types correct?
  • Are strings within allowed length?
  • Are enum values valid?

Invalid requests return 400 Bad Request before reaching the backend. This protects your backend from invalid input errors and reduces load.

5. Bot Protection and Anomaly Detection

  • Bot Detection: User-Agent analysis, headless browser detection, CAPTCHA challenges
  • Behavioral Analysis: Flags unusual patterns like 1000 logins in 1 second from one IP
  • Geo-Blocking: Blocks requests from specific countries
  • IP Reputation: Blocks known malicious IPs using threat intelligence feeds

6. mTLS (Mutual TLS)

With mTLS, not only does the client authenticate to the server—the server also authenticates to the client. Both sides present certificates. The gateway can require and validate client certificates, which is more secure than API keys since certificates are harder to steal and expire automatically.

Use cases: B2B APIs, internal service-to-service communication, regulated industries (banking, healthcare).

7. Audit Logging and Security Monitoring

The gateway logs every request:

  • Who (consumer ID, IP address)
  • When (timestamp)
  • What (endpoint, method)
  • How (status code, latency)
  • Why denied (which security rule triggered)

These logs feed into SIEM systems, alerting, and compliance audits.

Why API Gateway Security Matters in Practice

Scenario 1: Credential Stuffing

An attacker tries 10,000 stolen password/email combinations against a login endpoint. Without gateway rate limiting, all 10,000 requests go through. With per-IP rate limiting (5 login attempts per minute), 9,995 get blocked.

Scenario 2: API Scraping

A competitor writes a bot to query the /api/products endpoint at high frequency to scrape your entire catalog. Without quotas and bot detection, they get everything. With token bucket limiting (100 req/min) and bot detection (headless browser detection), the bot gets blocked.

Scenario 3: Internal Service Exposure

A backend service accidentally implemented an admin endpoint without authentication checks. Without mandatory gateway authentication for all endpoints, the endpoint becomes publicly accessible. With centralized gateway authentication, every request is authenticated—including the forgotten endpoint.

Real-World Example: Kong API Gateway Security Configuration

This example demonstrates a complete security setup for Kong: JWT authentication, per-consumer rate limiting, CORS, IP restrictions, request size limits, and audit logging. It’s instructive because it unifies all four security domains—access control, traffic control, threat protection, and hardening—in a declarative configuration.

# kong-security.yml
# Complete security configuration for a Kong API Gateway

services:
  - name: payment-api
    url: http://payment-service.internal:3000
    routes:
      - name: payment-route
        paths:
          - /api/payments
        methods:
          - GET
          - POST
          - DELETE
        strip_path: false

  - name: user-api
    url: http://user-service.internal:3001
    routes:
      - name: user-route
        paths:
          - /api/users
        methods:
          - GET
          - POST
          - PUT
        strip_path: false

plugins:
  # --- 1. ACCESS CONTROL ---

  # JWT authentication for all routes
  - name: jwt
    config:
      secret_is_base64: false
      run_on_preflight: true
      maximum_expiration: 3600
      header_names:
        - Authorization

  # ACL for role-based access control
  - name: acl
    config:
      allow:
        - admin
        - user
      hide_groups_header: false

  # --- 2. TRAFFIC CONTROL ---

  # Rate limiting: 100 req/min per consumer, 1000 req/h
  - name: rate-limiting
    config:
      minute: 100
      hour: 1000
      policy: redis
      redis_host: redis.internal
      redis_port: 6379
      limit_by: consumer
      fault_tolerant: true
      retry_after: true

  # Request size limiting: max 1MB body
  - name: request-size-limiting
    config:
      allowed_size: 1000000
      size_unit: bytes

  # --- 3. THREAT PROTECTION ---

  # CORS: only allowed origins
  - name: cors
    config:
      origins:
        - https://app.example.com
        - https://admin.example.com
      methods:
        - GET
        - POST
        - PUT
        - DELETE
      headers:
        - Authorization
        - Content-Type
        - X-Request-ID
      credentials: true
      max_age: 3600

  # IP restriction: only known IP ranges
  - name: ip-restriction
    config:
      allow:
        - 10.0.0.0/8
        - 192.168.0.0/16
        - 203.0.113.0/24

  # Request transformer: add security headers
  - name: response-transformer
    config:
      add:
        headers:
          - Strict-Transport-Security:max-age=31536000; includeSubDomains
          - X-Content-Type-Options:nosniff
          - X-Frame-Options:DENY
          - Cache-Control:no-store

  # --- 4. HARDENING ---

  # Prometheus metrics for security monitoring
  - name: prometheus
    config:
      per_consumer: true
      status_code_metrics: true
      latency_metrics: true

  # Audit logging via HTTP log plugin
  - name: http-log
    config:
      http_endpoint: https://siem.internal/api/logs
      method: POST
      timeout: 5000
      keepalive: 30000
      retry_count: 3

consumers:
  - username: web-app
    acls:
      - group: user
    jwt_secrets:
      - key: web-app-key
        secret: ${WEB_APP_SECRET}

  - username: admin-panel
    acls:
      - group: admin
    jwt_secrets:
      - key: admin-key
        secret: ${ADMIN_SECRET}
// jwt-validation.js
// Example: JWT validation with scope checking (Node.js)
// This is how a custom plugin or backend might extend validation

const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');

// JWKS client for key rotation
const client = jwksClient({
  jwksUri: 'https://auth.example.com/.well-known/jwks.json',
  cache: true,
  cacheMaxEntries: 10,
  cacheMaxAge: 36000000
});

function getKey(header, callback) {
  client.getSigningKey(header.kid, (err, key) => {
    if (err) return callback(err);
    callback(null, key.getPublicKey());
  });
}

function validateToken(token, requiredScopes) {
  return new Promise((resolve, reject) => {
    jwt.verify(token, getKey, {
      algorithms: ['RS256'],
      audience: 'api.example.com',
      issuer: 'https://auth.example.com'
    }, (err, decoded) => {
      if (err) {
        reject({ code: 'INVALID_TOKEN', message: err.message });
        return;
      }

      // Scope check: token must contain all required scopes
      const tokenScopes = decoded.scope ? decoded.scope.split(' ') : [];
      const hasAllScopes = requiredScopes.every(s => tokenScopes.includes(s));

      if (!hasAllScopes) {
        reject({
          code: 'INSUFFICIENT_SCOPES',
          message: `Required scopes: ${requiredScopes.join(', ')}`
        });
        return;
      }

      // Token is valid and has all scopes
      resolve(decoded);
    });
  });
}

// Middleware for Express
function requireScopes(...scopes) {
  return async (req, res, next) => {
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        error: 'UNAUTHORIZED',
        message: 'Bearer token required'
      });
    }

    try {
      const decoded = await validateToken(authHeader.split(' ')[1], scopes);
      req.user = decoded;
      next();
    } catch (err) {
      const status = err.code === 'INSUFFICIENT_SCOPES' ? 403 : 401;
      res.status(status).json({
        error: err.code,
        message: err.message
      });
    }
  };
}

Detailed Context

Gateway Hardening: Protecting the Gateway Itself

The gateway is itself an attack surface. Key hardening practices include:

  • Secure the admin API: The gateway’s management API (for example, Kong Admin API on port 8001) must never be publicly accessible. Restrict it to VPN, VPC, or localhost only.
  • Secret management: Store secrets (JWT secrets, API keys, TLS keys) in a vault system—AWS Secrets Manager, HashiCorp Vault, or Kubernetes Secrets—not in plaintext configuration files.
  • TLS hardening: Enable only TLS 1.2 and 1.3, disable legacy cipher suites, and set HSTS headers.
  • DDoS protection: Place Cloudflare or AWS Shield in front of the gateway for volumetric DDoS defense.
  • Configuration as code: Version gateway configuration in Git and deploy changes through CI/CD. Avoid manual production changes.

Zero Trust at the API Gateway

In a Zero Trust model, the gateway trusts nothing. Every request is authenticated, including internal ones. Every connection uses encryption (mTLS). Every request is logged. The gateway is not considered part of a trusted internal network—it’s part of your defense perimeter.

API Key Rotation

API keys must be rotatable. Best practice:

  • Keys have an expiration date
  • Rotate every 90 days or immediately if compromise is suspected
  • Grace period: both old and new keys are valid during migration
  • Notify consumers automatically before expiration

Security Headers at the Gateway

The gateway sets central security headers on all responses:

HeaderValuePurpose
Strict-Transport-Securitymax-age=31536000; includeSubDomainsEnforce HTTPS
X-Content-Type-OptionsnosniffPrevent MIME sniffing
X-Frame-OptionsDENYPrevent clickjacking
Cache-Controlno-storeNo caching of sensitive data
X-Rate-Limit-Limit100Transparent rate limit info
X-Rate-Limit-Remaining87Remaining requests

Monitoring and Alerting

The gateway should trigger alerts for:

  • Sudden spikes in 401/403 responses (potential attack)
  • Rate limit exceedances (potential abuse)
  • Unusual traffic from a single IP or consumer
  • Backend error rates exceeding threshold
  • Admin API access attempts

FAQ: API Gateway Security

1. Why should authentication happen at the API Gateway rather than in the backend?

Centralized authentication at the gateway ensures all APIs enforce the same security standard. The backend is freed from that responsibility and can focus on business logic. Unauthenticated requests never reach the backend in the first place. This reduces the risk of bugs, since missed auth checks in the backend get caught by the gateway instead.

2. What’s the difference between rate limiting and quotas?

Rate limiting restricts the number of requests within a time window (for example, 100 per minute). Quotas cap total usage over a longer period (for example, 10,000 per month). Rate limiting protects against real-time overload, while quotas govern overall consumption and enable monetization strategies like free versus paid tiers.

3. What is mTLS and when should you use it?

mTLS (Mutual TLS) requires both client and server to present and validate certificates. It’s used for B2B APIs, internal service-to-service communication, and in heavily regulated industries. mTLS is more secure than API keys since certificates are harder to steal and automatically expire.

4. How does schema validation work at the API Gateway?

The gateway validates every request against an OpenAPI schema. It checks for required fields, correct data types, string lengths within bounds, and valid enum values. Invalid requests are rejected with a 400 Bad Request before reaching the backend. This protects the backend and reduces its load.

5. What is a WAF and how does it differ from schema validation?

A WAF (Web Application Firewall) detects and blocks attack patterns like SQL injection, XSS, and path traversal. Schema validation checks request structure against a schema. The WAF protects against malicious content, while schema validation protects against structurally invalid requests. Both complement each other and should be deployed together.

6. How do you secure the API Gateway’s admin API?

The admin API must not be publicly accessible. Restrict it to VPN, VPC-internal networks, or localhost only. Require separate authentication like dedicated admin tokens or mTLS. Configuration changes should flow through CI/CD from version-controlled code rather than through manual admin API calls.

7. What is bot protection at the API Gateway?

Bot protection includes user-agent analysis, headless browser detection, CAPTCHA challenges, and behavioral analysis. The gateway identifies automated bots scraping APIs or performing credential stuffing, then blocks or challenges them. This is supplemented by IP reputation checks and geo-blocking.

8. How do you safely rotate API keys?

API keys should have expiration dates and be rotated regularly (for example, every 90 days). During rotation, both old and new keys remain valid temporarily (grace period) to allow clients to update. Consumers are notified before expiration. If a key is suspected compromised, it’s revoked immediately and rotated out of band.

9. What is Zero Trust in the context of an API Gateway?

In the Zero Trust model, the gateway trusts no one—not even internal services. Every request is authenticated and authorized, every connection is encrypted with mTLS, and every request is logged. There is no trusted internal network. The gateway forms part of the security perimeter, not a trusted zone.

10. What security headers should the API Gateway set?

Set Strict-Transport-Security (HSTS) to enforce HTTPS, X-Content-Type-Options: nosniff to prevent MIME sniffing, X-Frame-Options: DENY to block clickjacking, and Cache-Control: no-store to prevent caching sensitive data. Also include rate limit headers (X-Rate-Limit-Limit, X-Rate-Limit-Remaining) for client transparency.

11. How does gateway security differ from backend security?

The gateway handles network-level security: authentication, rate limiting, WAF, and TLS. The backend handles application-specific security: ownership checks, business rule validation, and database security. The gateway blocks unauthorized requests before they reach the backend. The backend verifies that the authenticated user can access the specific resource.

12. What happens if the gateway fails?

A gateway outage makes the entire API unreachable (single point of failure). Protect against this by running multiple gateway instances behind a load balancer, enabling automatic failover, performing health checks, and using auto-scaling. Store gateway configuration in a database or Git so new instances can load it quickly.

13. How do you integrate OAuth 2.0 into the API Gateway?

The gateway acts as an OAuth resource server. It validates access tokens either through introspection (sending the token to the authorization server) or by JWKS verification (checking the signature with the authorization server’s public key). Define required scopes per endpoint. The gateway forwards claims to the backend as headers.

14. What is IP whitelisting at the API Gateway?

IP whitelisting allows requests only from known IP addresses or ranges. It’s used for B2B APIs (partner IPs only), internal APIs (VPC IPs only), and admin endpoints. Combined with authentication, it provides defense in depth: even with a stolen token, an attacker cannot connect from an unauthorized IP.

15. How do you implement audit logging at the API Gateway?

The gateway logs every request with consumer ID, IP, timestamp, endpoint, method, status code, and latency. For rejected requests, it logs the triggered security rule. Logs are sent to a SIEM system (Security Information and Event Management). Alerts trigger on anomalous patterns, such as a sudden spike in 401 responses.

Continue Your API Learning Path

The next article covers API Gateway Patterns — architectural patterns like Backend for Frontend, API Composition, Protocol Translation, and Aggregation, all implemented at the gateway layer.

References and Further Reading

  1. https://docs.konghq.com/hub/
  2. https://owasp.org/API-Security/
  3. https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-policies
  4. https://docs.aws.amazon.com/apigateway/latest/developerguide/
  5. https://www.cloudflare.com/learning/ddos/glossary/web-application-firewall-waf/

API Development

Books about API design, REST, GraphQL, OpenAPI and API architecture

Designing Data-Intensive Applications von Martin Kleppmann

Designing Data-Intensive Applications von Martin Kleppmann

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

API Design Patterns von JJ Geewax

API Design Patterns von JJ Geewax

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

Back to Blog
Share:

Related Posts