API Security API Gateways
An API gateway is a server that sits between clients and your backend API services. Every API request passes through the gateway before reaching your application. This single entry point becomes a powerful place to enforce security policies, authenticate requests, rate limit traffic, and filter malicious inputs — all before they ever touch your business logic.
The API Gateway as a Bouncer
Without an API Gateway: Client 1 ──→ API Service A Client 2 ──→ API Service A Client 3 ──→ API Service B Client 4 ──→ API Service B Every service must implement its own: - Authentication - Rate limiting - Logging - CORS - SSL termination → Duplicated effort, inconsistent security. With an API Gateway: Client 1 ──→ ┌─────────────────┐ ──→ API Service A Client 2 ──→ │ API Gateway │ ──→ API Service A Client 3 ──→ │ (Bouncer) │ ──→ API Service B Client 4 ──→ └─────────────────┘ ──→ API Service B Gateway handles: - Authentication for ALL services - Rate limiting for ALL services - Logging for ALL services - SSL termination - Request routing → Single, consistent security layer.
Security Functions of an API Gateway
Function 1: Authentication and Authorization
Gateway validates every token before forwarding the request.
Flow:
Client sends: GET /api/orders + Authorization: Bearer TOKEN
Gateway step 1: Validate TOKEN
→ Call identity provider to verify JWT signature
→ Check expiry, issuer, audience
→ Extract user_id and role from token payload
Gateway step 2: Check authorization policy
→ Is role "customer" allowed to GET /api/orders? Yes.
→ Is role "customer" allowed to DELETE /api/orders? No → Return 403.
Gateway step 3: Forward enriched request to backend
→ Adds headers: X-User-Id: 101, X-User-Role: customer
→ Backend trusts these headers (internal network only)
→ Backend does NOT need to re-validate the token.
Backend focus: Business logic only. Auth handled by gateway.
Function 2: Rate Limiting
Centralized rate limiting at the gateway protects all backend services.
Gateway config example (Kong):
plugins:
- name: rate-limiting
config:
minute: 100 # 100 requests per minute per user
hour: 5000 # 5000 requests per hour per user
policy: redis # Use Redis for distributed counting
limit_by: consumer # Limit per authenticated user
Route-specific limits:
/api/login:
minute: 5 # Strict limit on login endpoint
/api/products:
minute: 500 # Higher limit for product browsing
Function 3: SSL/TLS Termination
The gateway handles SSL/TLS, decrypts traffic, and communicates with backend services over an internal network. Internet (Encrypted) Internal Network (May be encrypted) Client ──HTTPS──→ Gateway ──HTTP or HTTPS──→ Backend Service Benefits: Backend services do not need their own TLS certificates. Simplifies certificate management (one cert for gateway). Gateway can inspect decrypted traffic for security policies. Security consideration: Internal network between gateway and backends should also be encrypted (mTLS) if those services contain sensitive data. "Internal" does not mean "safe" — insider threats and lateral movement attacks target internal networks.
Function 4: Web Application Firewall (WAF)
A WAF integrated into the gateway inspects request content for known attack patterns and blocks them before reaching the API. WAF detects and blocks: SQL Injection patterns: ' OR 1=1--, UNION SELECT XSS patterns: <script>, javascript:, onerror= Command injection: ; cat /etc/passwd, | whoami Path traversal: ../../../etc/passwd XXE patterns: <!DOCTYPE, <!ENTITY, SYSTEM "file:// Known vulnerability exploits (CVEs) WAF Modes: Detection mode: Logs attacks but lets them through. Use during setup. Prevention mode: Blocks attacks. Use in production. Limitation: WAFs are signature-based. Novel attacks or evasion techniques (encoding, obfuscation) may bypass WAF rules. WAF = one layer. Not a replacement for secure code.
Function 5: Request and Response Transformation
Gateways can modify requests before forwarding and modify responses before returning to clients. Request transformation uses: Add security headers: X-Request-ID, X-Forwarded-For Remove sensitive headers the client should not send: internal headers Validate and enforce request schema Response transformation uses: Add security headers: Strict-Transport-Security, X-Content-Type-Options Remove sensitive internal headers the backend added: server version info Mask sensitive fields before returning to client (e.g., mask card numbers) Response header injection: Gateway adds to every response: Strict-Transport-Security: max-age=31536000; includeSubDomains X-Content-Type-Options: nosniff X-Frame-Options: DENY Cache-Control: no-store (on sensitive endpoints) One configuration at the gateway → applies to all backend services.
Function 6: IP Allowlisting and Geo-Blocking
Gateway can restrict access based on source IP or geography. IP Allowlisting: Admin API endpoints accessible only from: - Company office IP ranges: 203.0.113.0/24 - VPN server IP: 198.51.100.10 All other sources → 403 Forbidden before authentication even runs. Geo-Blocking: If your service is India-only, block all traffic from: - Countries where you have no customers - Known high-risk source regions for your threat model Be careful: legitimate users use VPNs and may appear from other countries. Use soft blocking (require additional verification) over hard blocking for most cases. IP Reputation Filtering: Commercial threat intelligence feeds maintain lists of: - Known malicious IPs - Tor exit nodes - VPN/proxy services - Botnet C2 servers Gateway checks incoming IP against these lists. High-risk IPs blocked or challenged with CAPTCHA.
Popular API Gateway Solutions
Cloud-Managed (No infrastructure to maintain): AWS API Gateway: Deep integration with AWS services, Lambda, IAM. Google Cloud Apigee: Enterprise features, advanced analytics. Azure API Management: Integrated with Azure AD for enterprise auth. Cloudflare API Shield: Edge-based, DDoS protection, WAF included. Self-Hosted Open Source: Kong Gateway: Lua plugins, PostgreSQL backend, very extensible. Nginx + OpenResty: High performance, configurable via Lua. Traefik: Cloud-native, auto-discovers Docker/Kubernetes services. Envoy: High-performance proxy, used in Istio service mesh. Choosing factors: Cloud vs self-hosted: Managed services reduce ops burden. Performance requirements: Requests per second, latency targets. Feature needs: WAF, developer portal, analytics, monetization. Existing infrastructure: AWS shop → AWS API Gateway; K8s → Envoy/Kong.
Gateway in a Microservices Architecture
In microservices, there may be hundreds of internal service-to-service
API calls in addition to external client calls.
External Gateway (North-South Traffic):
Handles traffic from internet clients to backend services.
Full security suite: auth, rate limiting, WAF, logging.
Internal Service Mesh (East-West Traffic):
Handles traffic between internal microservices.
Uses mutual TLS (mTLS) for service-to-service authentication.
Manages service discovery, load balancing, circuit breaking.
Tools: Istio, Linkerd, Consul Connect.
┌────────────────────────────────────────────────────┐
│ External Zone │
│ Internet Clients → [API Gateway] → Internal Zone │
└────────────────────────────────────────────────────┘
↓
┌────────────────────────────────────────────────────┐
│ Internal Zone │
│ [Service A] ←→mTLS←→ [Service B] │
│ [Service B] ←→mTLS←→ [Service C] │
│ (Service Mesh manages internal security) │
└────────────────────────────────────────────────────┘
Gateway Security Pitfalls
Pitfall 1: Trusting Gateway-Injected Headers from External Clients Gateway adds X-User-Id header before forwarding to backend. But what if an external client sends X-User-Id: 1 (admin) directly? Fix: Gateway strips any X-User-* headers from incoming requests before adding its own verified values. Pitfall 2: Backend Services Accessible Without Gateway If backend services are directly reachable from the internet, the gateway is bypassed entirely. Fix: Backend services should only accept connections from gateway IP ranges. Use network security groups and firewalls. Pitfall 3: Gateway as Single Point of Failure If the gateway goes down, all APIs go down. Fix: Run multiple gateway instances behind a load balancer. Implement circuit breakers for gateway-to-backend connections. Pitfall 4: Outdated Gateway Configuration New API endpoints added to backend but not registered in gateway. These unregistered endpoints may be reachable directly or with incorrect gateway policies. Fix: Automated synchronization between API specification (OpenAPI) and gateway configuration.
Key Points
- An API gateway is a centralized entry point that enforces security policies — authentication, rate limiting, WAF, logging — for all backend services from one place.
- Gateways handle SSL termination, reducing certificate management complexity for backend services.
- Gateway-injected headers (X-User-Id, X-User-Role) enable backends to trust user identity without re-validating tokens — but gateways must strip these headers from incoming client requests.
- Backend services should only be reachable through the gateway. Direct internet access to backends bypasses all gateway security controls.
- Service mesh (Istio, Linkerd) handles internal service-to-service security using mTLS, complementing the external API gateway.
