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

API Gateway Security: Authentication & Rate Limiting

Secure your APIs with OAuth, JWT, rate limiting, WAF, mTLS, IP whitelisting and audit logging best practices.

S

schutzgeist

13 min read
API Gateway Security: Authentication & Rate Limiting

API Gateway Security: Authentication, Threat Protection and Hardening

The API Gateway is the single entry point for all API traffic. When it’s insecure, everything behind it is at risk. When configured properly, 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 routed through it from attacks, abuse, and misconfiguration. Since the gateway is your only external entry point, it’s the ideal place to enforce security policies centrally.

Security at the API Gateway spans 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 protection, audit logs)

Who Uses API Gateway Security?

  • Platform teams set central security policies for 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)

Why This Matters for IT Professionals and Exams

API Gateway security is a core topic in cloud certifications (AWS Certified Security, Azure Security Engineer) and OWASP API Security Top 10. In professional exams, you’ll frequently see questions about centralized versus decentralized authentication. The architectural decision to centralize security at the gateway reduces complexity and failure points—but it becomes a single point of failure if not properly hardened.

Core Concepts in Depth

1. Centralized Authentication at the Gateway

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

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 executes authorization logic

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

OAuth 2.0 Integration

The gateway can act as an OAuth Resource Server. It validates access tokens against the authorization server (using introspection or JWKS verification). Each endpoint specifies which scopes are required:

  • /api/orders — Scope orders:read for GET, orders:write for POST
  • /api/admin/users — Scope admin:users

API Key Management

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

2. Rate Limiting and Quotas

Rate limiting at the gateway is your first line of defense against abuse. It differs from reverse-proxy rate limiting through its granularity:

  • Per consumer: Each API key has its own limit
  • Per endpoint: Critical endpoints have lower limits
  • Per combination: A consumer gets 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 per time window (e.g., 100 per minute). Simple, but allows bursts at window boundaries.
  • Sliding Window: A moving time window for smoother distribution.
  • Token Bucket: The bucket fills with tokens per time unit; each request consumes one token. Allows bursts until the bucket empties.

When exceeded: 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 your backend:

  • SQL Injection: Block patterns like ' OR 1=1 -- in query parameters
  • XSS: Detect and block <script> tags in inputs
  • Path Traversal: Block ../../etc/passwd in URL paths
  • Command Injection: Catch ; rm -rf / in parameters
  • Anomaly Detection: Flag 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: whitelists for critical endpoints, blacklists 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 lengths?
  • Are enum values valid?

Invalid requests are rejected with 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: Analyze user agents, detect headless browsers, serve CAPTCHA challenges
  • Behavioral Analysis: Spot unusual access patterns (e.g., 1000 logins in 1 second from one IP)
  • Geo-Blocking: Block requests from specific countries
  • IP Reputation: Block known malicious IPs using threat intelligence feeds

6. mTLS (Mutual TLS)

With mTLS, both clients and servers authenticate each other. Both sides present certificates. The gateway can require and validate client certificates—more secure than API keys since certificates are harder to steal and expire automatically.

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

7. Audit Logging and Security Monitoring

The gateway logs every request:

  • Who (consumer ID, IP)
  • When (timestamp)
  • What (endpoint, method)
  • How (status code, latency)
  • Why rejected (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 your login endpoint. Without gateway rate limiting, all 10,000 requests get through. With consumer-based rate limiting (5 login attempts per minute per IP), 9,995 get blocked.

Scenario 2: API Scraping

A competitor writes a bot that hammers your /api/products endpoints 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 recognition), the bot gets blocked.

Scenario 3: Internal Service Exposure

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

Practical 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 limiting, and audit logging. It was chosen because it unifies the four security domains (access control, traffic control, threat protection, hardening) into a single 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: Allow only specified 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: Allow 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 shows how a custom plugin or backend would 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 Information

Gateway Hardening: Protecting the Gateway Itself

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

  • Protect the admin API: The gateway’s management interface (e.g., Kong Admin API on port 8001) must not be publicly accessible. Restrict access to VPN, VPC, or localhost only.
  • Secret management: Never store secrets (JWT keys, API keys, TLS certificates) in plaintext configuration files. Use Vault, AWS Secrets Manager, or Kubernetes Secrets instead.
  • TLS hardening: Enforce TLS 1.2 and 1.3 only, disable legacy cipher suites, set HSTS headers.
  • DDoS protection: Place Cloudflare or AWS Shield in front of the gateway for volumetric DDoS mitigation.
  • Infrastructure as code: Version gateway configuration in Git, deploy changes through CI/CD pipelines, never modify production manually.

Zero Trust at the API Gateway

In a Zero Trust model, the gateway trusts no one. Every request is authenticated, even internal ones. All connections use encryption (mTLS). Every request is logged. The gateway itself is not considered part of a trusted inner network—it forms part of the defense perimeter.

API Key Rotation

API keys must be rotatable. Best practice includes:

  • Keys have an expiration date
  • Rotation every 90 days or immediately upon suspected compromise
  • Grace period: both old and new keys work in parallel during migration
  • Automated notifications to consumers before expiration

Security Headers at the Gateway

The gateway sets central security headers for all responses:

HeaderValuePurpose
Strict-Transport-Securitymax-age=31536000; includeSubDomainsEnforces HTTPS
X-Content-Type-OptionsnosniffPrevents MIME sniffing
X-Frame-OptionsDENYPrevents clickjacking
Cache-Controlno-storeNo caching of sensitive data
X-Rate-Limit-Limit100Transparent rate limit quota
X-Rate-Limit-Remaining87Remaining requests

Monitoring and Alerting

The gateway should trigger alerts for:

  • Sudden spikes in 401/403 responses (potential attack)
  • Rate limit violations (potential abuse)
  • Unusual traffic patterns from a single IP or consumer
  • Backend error rates exceeding thresholds
  • 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 maintain consistent security standards. The backend is freed from auth overhead and can focus on business logic. Unauthenticated requests never reach the backend in the first place. This reduces bugs—forgotten auth checks in backend code get caught at the gateway layer.

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

Rate limiting caps requests per time window—for example, 100 per minute. Quotas limit total requests over a longer period, such as 10,000 per month. Rate limiting protects against real-time overload, while quotas meter overall usage and enable monetization models (free tier versus paid tier).

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

Mutual TLS (mTLS) requires both client and server to present and validate certificates. Use it for B2B APIs, internal service-to-service communication, and in heavily regulated industries. mTLS is stronger than API keys because certificates are harder to steal and expire automatically.

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 length limits, and valid enum values. Invalid requests are rejected with 400 Bad Request before reaching the backend. This shields your backend and reduces unnecessary load.

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

A Web Application Firewall (WAF) 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 payload content; schema validation protects against structurally invalid requests. Both complement each other and should be deployed together.

6. How do you secure the admin API of your API Gateway?

The admin API must not be publicly accessible. Expose it only via VPN, VPC-internal networks, or localhost. Add separate authentication—dedicated admin tokens or mTLS. Apply configuration changes through CI/CD pipelines from version-controlled code, not 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 running credential stuffing attacks, then blocks or challenges them. Pair this with 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 instance, every 90 days. During rotation, both old and new keys remain valid for a grace period, giving clients time to switch. Notify consumers before expiry. If you suspect compromise, immediately rotate with full revocation of the old key.

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

Zero Trust means the gateway trusts no one—not even internal services. Every request is authenticated and authorized; every connection is encrypted with mTLS; every request is logged. There is no trusted internal network. The gateway forms part of your defense line, not a trusted zone.

10. Which security headers should your API Gateway set?

Use Strict-Transport-Security (HSTS) to enforce HTTPS, X-Content-Type-Options: nosniff to block MIME sniffing, X-Frame-Options: DENY to prevent clickjacking, and Cache-Control: no-store to prevent caching of sensitive data. Add 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 logic validation, and database hardening. The gateway blocks unauthorized requests before they reach your backend. The backend verifies that the authenticated user can access the specific resource.

12. What happens if your gateway fails?

A gateway outage makes your entire API unavailable—a single point of failure. Mitigate this by running multiple gateway instances behind a load balancer with automatic failover, health checks, and auto-scaling. Store gateway configuration in a database or Git repository so new instances can quickly load it.

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

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

14. What is IP whitelisting at the API Gateway?

IP whitelisting allows requests only from known addresses or ranges. Use it 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?

Log every request with consumer ID, IP address, timestamp, endpoint, method, status code, latency, and the security rule that triggered any rejection. Stream logs to a SIEM system (Security Information and Event Management). Alert on anomalies—for example, sudden spikes in 401 responses.

Next in the API Learning Path

The next article covers API Gateway Patterns — architectural patterns like Backend for Frontend, API Composition, Protocol Translation, and Aggregation that are 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