C

Web › Module 2 › Lesson 4

BeginnerModule 2Lesson 4/6

Prevention Methods

Output encoding, CSP, CSRF tokens, and SameSite cookies for XSS and CSRF defense

15 min+56 XP3 quiz
Module progress4 of 6

Visual · web_developer

Layer encoding, headers, and tokens so attacker input stays inert and forged requests fail validation.

Opening

Encode, tokenize, cookie-harden

XSS and CSRF share a theme: never trust the browser to police itself. For XSS, stop scripts at the sink with context-aware encoding and Content Security Policy. For CSRF, require secrets the attacker's site cannot guess—synchronizer tokens and SameSite cookies.

1. XSS Prevention — Output Encoding

Safe HTML output (Python/Jinja example)# Auto-escape enabled in template engine <p>Hello {{ username }}</p> # Renders &lt;script&gt; as text, not executable tag # Avoid: Markup("Hello " + user_input) # bypasses escape

# Auto-escape enabled in template engine
<p>Hello {{ username }}</p>
# Renders &lt;script&gt; as text, not executable tag

# Avoid: Markup("Hello " + user_input)  # bypasses escape

Use framework defaults (React JSX escapes text, Django/Jinja autoescape). For rich text, sanitize with a vetted library (DOMPurify)—never roll your own regex filter.

2. Content Security Policy (CSP) Basics

Strict CSP header exampleselfselfnoneself

selfselfnoneself

CSP tells the browser which script sources are allowed. Even if XSS injects inline script, a strict script-src without unsafe-inline blocks execution. Start report-only in production, tune for your assets, then enforce.

3. CSRF Prevention

  • Synchronizer token

    Hidden field or header with a random secret tied to the session; server rejects requests without a valid token.

  • SameSite cookies

    SameSite=Lax or Strict reduces cross-site cookie sending on many CSRF vectors.

  • Double-submit / custom headers

    APIs requiring X-Requested-With or Authorization headers block simple form CSRF.

CSRF token in a form (concept)<form method="POST" action="/change-email"> <input type="hidden" name="csrf_token" value="{{ session.csrf_token }}"> <input name="email" type="email"> <button type="submit">Save</button> </form>

<form method="POST" action="/change-email">
  <input type="hidden" name="csrf_token" value="{{ session.csrf_token }}">
  <input name="email" type="email">
  <button type="submit">Save</button>
</form>

Defense stack

HttpOnly cookies stop JavaScript cookie theft from XSS but do not stop CSRF. Use encoding + CSP for XSS, tokens + SameSite for CSRF, and fix XSS promptly—it bypasses CSRF protections.

Knowledge Check

1

Context-aware output encoding prevents:

Multiple choice

Knowledge Check

2

True or False: SameSite=Lax cookies help mitigate many CSRF attacks.

True or False

Knowledge Check

3

A strict CSP script-src without unsafe-inline mainly blocks:

Multiple choice

← Previous

Answer all 3 knowledge checks to continue. (0/3 answered)