4 Hours

13. CORS, CSRF & XSS Protection

Web Security

Cross-Origin Resource Sharing (CORS), Cross-Site Request Forgery (CSRF), and Cross-Site Scripting (XSS) are among the most common web security vulnerabilities. This module covers understanding these attacks and implementing effective protections.

What is CORS?

CORS is a security mechanism that controls which origins can access your API. Browsers enforce the same-origin policy by default, blocking requests to different domains.

Text
Same-Origin Policy (Default):
- http://example.com → http://example.com/api  Allowed
- http://example.com → https://example.com     Different protocol
- http://example.com → http://api.example.com  Different subdomain
- http://example.com → http://another.com      Different domain
Why CORS exists: Without CORS, a malicious website could make requests to your bank's API using your authenticated session cookies.

Configuring CORS (Node.js)

JavaScript
const cors = require('cors');

// Development: allow localhost
const devCorsOptions = {
    origin: ['http://localhost:3000', 'http://localhost:5173'],
    credentials: true
};

// Production: strict origins only
const prodCorsOptions = {
    origin: ['https://myapp.com', 'https://api.myapp.com'],
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
    maxAge: 86400
};

app.use(cors(process.env.NODE_ENV === 'production' ? prodCorsOptions : devCorsOptions));
Never use origin: * in production! This allows any website to call your API. Always specify exact origins.

What is CSRF?

CSRF attacks trick users into executing unwanted actions on a website where they are authenticated.

Text
CSRF Attack Flow:
1. User logs into bank.com (gets session cookie)
2. User visits attacker.com without logging out
3. Attacker.com sends hidden request to bank.com/transfer?to=attacker&amount=1000
4. Browser automatically includes session cookie
5. Bank processes request as authenticated user

Result: Money transferred without user's knowledge!
Key insight: CSRF exploits the fact that browsers automatically send cookies with every request.

CSRF Protection: SameSite Cookies

The most effective modern CSRF protection is the SameSite cookie attribute.

Text
SameSite=Lax (Default in modern browsers):
- Cookie sent for top-level navigations (clicking a link)
- NOT sent for cross-site POST requests
- Blocks most CSRF attacks

SameSite=Strict (Most secure):
- Cookie NEVER sent for cross-site requests
- Best CSRF protection
- May break some legitimate cross-site links

SameSite=None (For cross-site APIs):
- Cookie sent for cross-site requests
- REQUIRES Secure flag (HTTPS only)
JavaScript
// Setting SameSite cookies in Express
res.cookie('sessionId', token, {
    httpOnly: true,
    secure: true,
    sameSite: 'strict',  // Best CSRF protection
    maxAge: 3600000
});

CSRF Tokens (Alternative Protection)

For APIs that cannot use SameSite cookies, implement CSRF tokens.

JavaScript
const csrf = require('csurf');

const csrfProtection = csrf({ cookie: true });

// Endpoint to get CSRF token
app.get('/api/csrf-token', csrfProtection, (req, res) => {
    res.json({ csrfToken: req.csrfToken() });
});

// Protect state-changing endpoints
app.post('/api/transfer', csrfProtection, (req, res) => {
    // CSRF token automatically validated
    processTransfer(req.body);
    res.json({ success: true });
});

// Client: fetch token first, then include in requests
const { csrfToken } = await fetch('/api/csrf-token').then(r => r.json());
fetch('/api/transfer', {
    method: 'POST',
    headers: { 'X-CSRF-Token': csrfToken },
    body: JSON.stringify(transferData)
});

What is XSS (Cross-Site Scripting)?

XSS attacks inject malicious scripts into web pages viewed by other users.

Text
XSS Attack Example:
1. Attacker posts comment: <script>stealCookies()</script>
2. Website stores comment in database
3. Other users view the page
4. Malicious script executes in their browsers
5. Attacker steals session cookies

Result: Attacker hijacks user sessions!
Three types: Reflected XSS (immediate in request), Stored XSS (saved in database), DOM-based XSS (client-side only).

XSS Protection: Output Encoding

Never insert user input directly into HTML. Always encode it.

JavaScript
// Dangerous - DO NOT DO THIS
app.get('/search', (req, res) => {
    const query = req.query.q;
    res.send(`<h1>Search results for: ${query}</h1>`);  // XSS vulnerability!
});

// Safe - escape HTML
function escapeHtml(str) {
    return str
        .replace(/&/g, '&')
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/"/g, '"')
        .replace(/'/g, ''');
}

app.get('/search', (req, res) => {
    const query = escapeHtml(req.query.q);
    res.send(``);  // Safe
});

XSS Protection: Content Security Policy (CSP)

CSP is the most powerful XSS defense. It tells the browser what sources of content are allowed.

JavaScript
app.use((req, res, next) => {
    res.setHeader('Content-Security-Policy', [
        "default-src 'self'",
        "script-src 'self' https://trusted-cdn.com",
        "style-src 'self' 'unsafe-inline'",
        "img-src 'self' data: https://images.unsplash.com",
        "font-src 'self'",
        "connect-src 'self' https://api.myapp.com",
        "frame-ancestors 'none'",
        "form-action 'self'"
    ].join('; '));

    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('X-Frame-Options', 'DENY');
    res.setHeader('X-XSS-Protection', '1; mode=block');

    next();
});
Helmet.js: Use the helmet package to set all security headers automatically.

Knowledge Check

Ready to test your understanding of 13. CORS, CSRF & XSS Protection?

Back