Assume Breach: The Core Principle of Zero-Trust
The perimeter-based security model ('inside the corporate network is safe, outside is hostile') is completely obsolete in modern cloud computing. Under Zero-Trust architecture, every single request—regardless of origin—must be authenticated, authorized, and cryptographically verified before touching a database record.
API security is not just an HTTPS certificate; it requires defense-in-depth across input validation, token integrity, rate limiting, and continuous anomaly detection.
A compromised internal microservice or third-party webhook sender should never have lateral access to customer data.
"Never trust, always verify, and continuously inspect every payload."
- Never store sensitive authentication tokens in browser localStorage; use HTTP-only, Secure SameSite cookies.
- Implement strict schema validation (using Zod or TypeBox) before controller logic executes.
- Enforce sliding-window rate limits backed by Redis to mitigate automated credential stuffing.
OAuth 2.1 and Token Security: Deprecating the Implicit Flow
OAuth 2.1 officially removes legacy security liabilities: the Implicit Grant and Resource Owner Password Credentials grant are deprecated. In their place, Authorization Code Flow with PKCE (Proof Key for Code Exchange) is mandatory for both Single Page Apps and native mobile clients.
Access tokens must have short lifespans (10-15 minutes), while refresh tokens are stored securely in encrypted HTTP-only cookies with automatic rotation: every time a refresh token is used, a new one is issued and the old one is immediately invalidated.
Sliding Window Rate Limiting with Redis
Simple fixed-window counters allow malicious actors to double their request burst right across boundary edges. Production API gateways implement Redis sliding-window algorithms to provide uniform request pacing.
This ensures that brute-force attacks and credential stuffing bots are throttled before they can stress internal database connection pools.
import { NextRequest, NextResponse } from "next/server";
import { Redis } from "@upstash/redis";
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
export async function rateLimit(req: NextRequest, limit = 60, windowSecs = 60) {
const ip = req.headers.get("x-forwarded-for") || "anonymous";
const now = Date.now();
const clearBefore = now - windowSecs * 1000;
const key = `rate_limit:${ip}`;
const pipeline = redis.pipeline();
pipeline.zremrangebyscore(key, 0, clearBefore);
pipeline.zadd(key, { score: now, member: `${now}-${Math.random()}` });
pipeline.zcard(key);
pipeline.expire(key, windowSecs);
const results = await pipeline.exec();
const requestCount = results[2] as number;
return {
isAllowed: requestCount <= limit,
remaining: Math.max(0, limit - requestCount),
currentUsage: requestCount
};
}Cryptographic Webhook Signatures (HMAC-SHA256)
When exposing public webhook endpoints for payment providers or logistics updates, never rely on secrecy of the URL. Always verify HMAC signatures using shared secret keys to guarantee that the payload was genuinely generated by the verified partner and was not tampered with in transit.