Defense in Depth for Cross-Site Attacks
What You'll Learn
You'll learn how combining multiple security layers creates robust protection against XSS, CSRF, and other cross-site attacks—even if one layer fails.
The Core Idea
Defense in depth means never relying on a single security control. For cross-site attacks, you stack protective layers so that if an attacker bypasses one defense, others still block the attack.
Think of it like protecting a castle: you don't just build a wall—you add a moat, guards, an inner keep, and locked doors. Each layer makes an attacker's job exponentially harder.
The Layered Approach to Cross-Site Security
Layer 1: Input Validation
Reject malicious data at entry points. Validate types, formats, and ranges before data enters your system.
Layer 2: Output Encoding
Escape data when rendering in HTML, JavaScript, or URLs. This neutralizes injected scripts even if validation missed something.
Layer 3: Content Security Policy (CSP)
Use CSP headers to restrict what scripts can execute and where resources load from. This blocks inline scripts attackers commonly inject.
Layer 4: CSRF Tokens
Require unique, unpredictable tokens for state-changing operations. This stops forged requests even if an attacker tricks a user into clicking.
Layer 5: SameSite Cookies
Set SameSite=Strict or SameSite=Lax to prevent cookies from being sent with cross-origin requests.
Layer 6: Secure Defaults
Use frameworks that encode by default, enable HTTPS-only cookies with Secure flag, and set HttpOnly to prevent JavaScript access.
Why This Matters
No single defense is perfect. Developers make mistakes, browsers have quirks, and attackers are creative. When you layer defenses, you create redundancy—multiple opportunities to stop an attack. If your encoding is imperfect, CSP catches it. If CSP misconfigures, tokens still block CSRF.
Key Takeaway: Defense in depth for cross-site attacks means combining input validation, output encoding, CSP, CSRF tokens, secure cookies, and secure defaults—creating overlapping protections that remain effective even when individual controls fail.