XSS and CSRF Explained: How They Work and How to Prevent Them

Cross-site scripting (XSS) and cross-site request forgery (CSRF) are two web vulnerabilities whose names sound alike and which beginners often confuse. They are different in an important way: XSS abuses the user’s trust in a website, by getting malicious script to run in the victim’s browser inside that site; CSRF abuses the website’s trust in the user’s browser, by making the browser send an unwanted request while the user is logged in. This lesson explains both, shows safe and unsafe code, and gives you lab practice in a deliberately vulnerable application.

Quick Comparison

XSSCSRF
Core ideaAttacker-controlled script runs in the victim’s browser, in the site’s contextVictim’s browser is tricked into sending a state-changing request
Needs the victim to be logged in?Not always, but impact is greater when they areYes, it relies on existing session cookies
Root causeUntrusted data placed into a page without proper encodingServer accepts requests without verifying they were intended
Main defenceContext-aware output encoding, Content Security PolicyAnti-CSRF tokens, SameSite cookies, re-authentication for sensitive actions

Part 1: Cross-Site Scripting

How XSS works

Imagine a site that shows a search term back to the user: “You searched for: [your text]”. If the application inserts that text directly into the HTML, then text containing HTML or script tags will be interpreted by the browser as part of the page. The injected script then runs with the same privileges as the site’s own scripts: it can read page content, act as the user, and in some cases access data that is not protected by HttpOnly.

The three types

TypeDescriptionExample scenario
ReflectedInput from the request is immediately included in the responseSearch page, error messages, URL parameters
StoredInput is saved by the server and shown to other users laterComments, profile fields, support tickets
DOM-basedClient-side JavaScript inserts untrusted data into the page unsafelyCode that writes location.hash into the page using innerHTML

A harmless test in your own lab

Security testers use a harmless marker to check whether input is reflected unencoded. In a deliberately vulnerable app running in your lab, a classic benign test string is shown below (displayed here as escaped text so that it does not run in this page):

<script>alert('test')</script>

If a vulnerable page displays a pop-up when this is entered, the input was not encoded. If it shows the literal text instead, the output is being encoded correctly. That single observation is the heart of an XSS test.

Vulnerable and safe code compared

# Python / Flask style illustration
from flask import Flask, request, render_template_string
from markupsafe import escape

app = Flask(__name__)

@app.route("/search-unsafe")
def search_unsafe():
    q = request.args.get("q", "")
    # DANGEROUS: raw input is placed straight into HTML
    return "<p>You searched for: " + q + "</p>"

@app.route("/search-safe")
def search_safe():
    q = request.args.get("q", "")
    # SAFE: output is HTML-encoded, so markup is shown as text
    return "<p>You searched for: " + str(escape(q)) + "</p>"

Better still, use a template engine that encodes by default (such as Jinja2 with autoescape on) and avoid APIs that bypass encoding.

XSS defences, in order of importance

  1. Context-aware output encoding. Encode data for the place it appears: HTML body, HTML attribute, JavaScript, URL or CSS each need different encoding.
  2. Use safe framework features. Modern frameworks (React, Angular, Vue) encode by default; avoid dangerouslySetInnerHTML, v-html, bypassSecurityTrust* and raw innerHTML unless the content has been sanitised.
  3. Sanitise rich text with a maintained library (for example DOMPurify) when HTML input is genuinely needed.
  4. Content Security Policy (CSP). A response header that tells the browser which script sources are allowed, greatly reducing XSS impact:
    Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'
  5. Cookie flags. HttpOnly prevents scripts from reading session cookies; Secure and SameSite add further protection.
  6. Input validation as an additional layer, not as the main defence.

Part 2: Cross-Site Request Forgery

How CSRF works

Browsers automatically attach a site’s cookies to any request sent to that site, including requests triggered from another website. Suppose you are logged in to an online banking site that changes an email address with a simple request. If the site only checks the session cookie, a malicious page you visit could cause your browser to send that same request, and the bank would believe you made it. The attacker never sees the response; CSRF works for state-changing actions such as changing settings, transferring funds or posting content.

CSRF defences

  1. Anti-CSRF tokens. The server includes an unpredictable, per-session or per-request token in each form and verifies it on submission. A third-party site cannot read or guess it.
    <form method="post" action="/change-email">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <input type="email" name="email">
      <button type="submit">Update</button>
    </form>
  2. SameSite cookies. SameSite=Lax or Strict instructs the browser not to send cookies on most cross-site requests. Modern browsers default to Lax, but explicit configuration is better.
    Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Lax; Path=/
  3. Use the right HTTP methods. Never change state with GET requests.
  4. Verify origin. Check the Origin or Referer header on state-changing requests as a supporting control.
  5. Re-authenticate for critical actions such as changing passwords or making payments.
  6. Custom headers for APIs. Requiring a custom header or JSON content type helps block simple cross-site form posts, but must be paired with correct CORS settings.

Note that XSS can defeat CSRF protections, because script running inside the site can read tokens. This is one reason XSS is treated as so serious.

Practice Lab 1: Reflected XSS in DVWA

  1. Start DVWA on 127.0.0.1 (see the home lab lesson). Set security to low.
  2. Open the “XSS (Reflected)” page. Enter your name and observe how it is shown.
  3. Enter the benign test marker above. Does a pop-up appear? Use the browser’s “view source” to see how the input appears in the HTML.
  4. Raise the security level to medium, high and impossible. For each level, read the source code the app displays and identify what changed (filtering, encoding, tokens).
  5. Write one sentence per level describing why it is or is not secure.

Practice Lab 2: Stored XSS and Cookie Flags

  1. Use the “XSS (Stored)” page to add a guestbook entry containing the harmless marker, then reload the page to see the effect on a “second user”.
  2. In developer tools, open Application (or Storage) and inspect the session cookie. Are HttpOnly, Secure and SameSite set?
  3. Explain why HttpOnly limits what a successful XSS can steal, and why it does not stop all harm.

Practice Lab 3: Understand CSRF Without Attacking Anyone

  1. In DVWA, open the CSRF page (the password-change form) at security level low.
  2. In developer tools, look at the Network tab as you submit the form. Notice that the request is a simple GET with the new password in the URL and no token.
  3. Reason about why that is dangerous: any page that causes your browser to request that URL would change your password.
  4. Compare with the impossible level, which requires the current password and a token. Note each control you see.

Practice Lab 4: Check Your Own Site’s Headers

curl -I https://yourdomain.example/
# Look for: Content-Security-Policy, Set-Cookie flags, X-Content-Type-Options, Referrer-Policy

Write a list of missing protections and a plan to add them. Test changes in a staging environment first, since an overly strict CSP can break legitimate scripts.

Common Mistakes

  • Trying to block XSS by removing the word script. Attackers have many other vectors; encode output instead.
  • Encoding for the wrong context (for example, HTML-encoding data placed inside JavaScript).
  • Marking user content as “safe” in a template to make formatting work.
  • Relying on SameSite alone for CSRF protection on sensitive actions.
  • Using GET requests for actions such as delete or transfer.

Practice Exercises

  1. Explain the difference between XSS and CSRF using a simple analogy of your own.
  2. For a comments feature, list where output encoding must be applied.
  3. Write a Content Security Policy for a site that loads scripts only from its own domain and one analytics provider.
  4. Describe how SameSite cookies, CSRF tokens and re-authentication work together to protect a password-change page.
  5. Review a small page you wrote and identify every place user input is shown back to a visitor.

Mentor tip: When you test, think “where does my input come out, and in what context?” The same text may be harmless in an HTML paragraph and dangerous inside an attribute or script block. Context is everything.

Educational use only: test for XSS or CSRF only on applications you own, deliberately vulnerable lab apps, or targets where you hold written permission.

Key takeaways
  • XSS runs attacker-supplied script in the victim’s browser; CSRF forges requests using the victim’s logged-in session.
  • Prevent XSS with context-aware output encoding, safe framework APIs, sanitisation and a strong CSP.
  • Prevent CSRF with anti-CSRF tokens, SameSite cookies, proper HTTP methods and re-authentication.
  • Set cookie flags: HttpOnly, Secure, SameSite.
  • Test only in your own lab or with explicit permission.

Related Lessons