Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 53 ยท Web Application Security

Cross-Site Scripting and CSRF Defense

Learn how reflected, stored and DOM XSS work, why output encoding, CSP and SameSite cookies matter, and how CSRF tokens block forged requests, with runnable models.

Two bug classes are named after the word "cross-site", and they are easy to confuse. Cross-site scripting (XSS) lets an attacker run their JavaScript inside your site's pages, so the script acts with the visitor's privileges on your origin. Cross-site request forgery (CSRF) lets an attacker's page make the visitor's browser send a request to your site, using the cookies the browser attaches automatically. XSS abuses the user's trust in a site, and CSRF abuses a site's trust in the browser.

This lesson explains both at the concept level and focuses on the defenses, which are well understood. The real browser behaviour (rendering, cookies, security headers) cannot run here, so those details are read-only. The runnable parts are stand-ins: a small HTML encoder and a CSRF token checker written in JavaScript, with fake data. They show the logic, not a production-ready library.

XSS in one picture

Untrusted text A comment, name or URL parameter.
Page output The server puts it into HTML.
Script runs The browser treats it as code.

The fix is to treat the text as text, every time.

1 / 3

Cross-site scripting

XSS arises when an application includes untrusted data in a page in a way that lets the browser interpret it as markup or script. Once a script runs on your origin, the same-origin policy is on its side: it can read the page, call your APIs as the user, change what the user sees and send data elsewhere. That is why XSS is treated as a serious flaw even when "nothing was hacked" on the server.

There are three common kinds:

  • Reflected XSS. The malicious value is part of the request (a search term in the URL) and the response echoes it back. The victim has to be lured into opening a crafted link.
  • Stored XSS. The value is saved (a comment, a profile name, a support ticket) and served to everyone who views it later. No lure is needed, and one saved payload can reach many users, including administrators.
  • DOM-based XSS. The server is not involved: client-side JavaScript reads data from the URL or another source and writes it into the page using a dangerous API, such as innerHTML or document.write.

The mechanism is the same in each case. The same text, such as <b>hi</b>, is harmless data when shown as text and live markup when inserted as HTML.

Defense 1: encode output for its context

The primary fix is contextual output encoding: convert characters that have meaning in the target context into a form that is displayed literally. In HTML text, < becomes &lt;, > becomes &gt;, & becomes &amp;, and quotes become entities when the value is placed in an attribute. The right encoding depends on where the value goes: HTML text, an attribute, a JavaScript string, a URL or CSS each have different rules. Modern template engines (Blade {{ }}, Jinja2, React's JSX) encode for the HTML context by default, so XSS usually returns when a developer turns that off ({!! !!}, |safe, dangerouslySetInnerHTML) or builds HTML by string concatenation.

The model below shows a vulnerable and an encoded way to build a comment list. It produces strings only, so there is nothing to execute. Compare the output carefully.

JS Output encoding for HTML

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the unsafe output the browser would see a real <img> element with an onerror handler. In the safe output the angle brackets and quotes are entities, so the browser shows the characters instead of creating elements. The attribute example is the reason quotes are encoded: without that, the nickname closes the value attribute and adds a new one.

This function is a teaching model for the HTML text and quoted-attribute contexts only. In real code, rely on your framework's default encoding and a well-tested sanitizer when you must allow some HTML (rich-text comments), and never write your own sanitizer for that purpose.

Defense 2: avoid dangerous sinks and use CSP

For DOM-based XSS the rule is to use APIs that treat input as text: element.textContent = value rather than element.innerHTML = value. Avoid eval, document.write and building inline event handlers from data.

A Content Security Policy (CSP) is a response header that tells the browser which sources of script, styles, images and frames are allowed. It is a safety net behind encoding, not a replacement for it. A strict policy might look like this (read-only):

HTTP
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'

With a policy like this, inline scripts without the current nonce do not run, so an injected <script> or onerror handler is blocked even if encoding was missed somewhere. Nonces must be random per response. Adding 'unsafe-inline' to script-src removes most of the protection.

Also mark session cookies HttpOnly so that, if XSS does occur, the script cannot read the session ID (see Authentication, Sessions and Access Control Flaws). The script can still make requests as the user, so HttpOnly limits the damage but does not stop the attack.

Cross-site request forgery

Browsers attach cookies to requests automatically, based on the destination, not on which page started the request. Suppose you are logged in to bank.example. A different site can include a hidden form that posts to https://bank.example/transfer. Your browser sends the request with your session cookie, and the bank sees a valid, logged-in request. The attacker cannot read the response (the same-origin policy still blocks that), but the state-changing action may already have happened.

sequenceDiagram
    participant U as Your browser
    participant B as bank.example
    participant E as other-site.example
    U->>B: Log in (session cookie stored)
    U->>E: Visit a page
    E-->>U: Page with a hidden form to bank.example
    U->>B: POST /transfer (cookie attached automatically)
    B-->>U: Transfer done

Forgery: the request is genuine from the server's view, but you did not intend it.

Defense 1: SameSite cookies

The SameSite cookie attribute tells the browser when to include a cookie on cross-site requests. SameSite=Lax (the default in current major browsers when the attribute is absent) omits the cookie from cross-site subrequests and from cross-site POST forms, but still sends it when the user follows an ordinary link to your site. SameSite=Strict omits it from every cross-site navigation. This blocks the classic attack by default, but it is best used together with tokens, because of subdomain issues, older browsers and any endpoint that changes state on GET.

Defense 2: CSRF tokens

A CSRF token is a random, unguessable value tied to the user's session. The server puts it in each form as a hidden field (or sends it for use in a request header), and rejects any state-changing request that does not carry the right value. The attacker's page cannot read your pages, so it cannot learn the token.

JS CSRF token issue and check

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The forged request carries the cookie, as a real forged request would, yet it is refused because it has no valid token. Notice the other design points: only POST can change state, and the token belongs to that session. In a real implementation the token is generated with a cryptographically secure random generator, compared in constant time, and framework middleware (Laravel's @csrf, Django's {% csrf_token %}) already handles it, so you rarely write this yourself. APIs authenticated with an Authorization header instead of cookies are not exposed to CSRF in the same way, because browsers do not attach that header automatically.

Do not test on real sites. Even a harmless-looking test string submitted to a site you do not own may be unauthorized. Practice XSS and CSRF only against deliberately vulnerable apps in your own home lab, and report findings from authorized tests through the process in Writing a Penetration Test Report.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Stored XSS is usually more dangerous than reflected XSS because:

    A stored payload needs no lure: it runs for everyone who loads the affected page, including administrators.
  2. 2. What is the primary defense against XSS?

    Encoding makes untrusted text display as text. CSP and HttpOnly add extra layers behind it.
  3. 3. Which DOM API is the safer choice for inserting untrusted text?

    textContent treats the value as plain text, so it cannot create elements or run handlers.
  4. 4. Why can't an attacker's page read a CSRF token from the victim's logged-in page?

    The forged request can be sent, but its response cannot be read across origins, so the token stays secret.
  5. 5. A CSRF attack works because:

    The cookie rides along on a forged request, so the server sees a valid session. Tokens and SameSite cookies break that.

Summary

  • XSS lets attacker-controlled script run on your origin; it comes in reflected, stored and DOM-based forms.
  • Encode output for its context; use textContent, avoid innerHTML, eval and document.write with untrusted data.
  • A strict CSP is a safety net, and HttpOnly cookies limit what a successful XSS can steal.
  • CSRF abuses automatically attached cookies to forge state-changing requests.
  • Use SameSite cookies, anti-forgery tokens and POST (never GET) for state changes.
  • Frameworks already provide encoding and CSRF middleware; the usual bugs come from turning them off.
  • Practice only in labs or authorized scopes.

Next: SSRF, Path Traversal, Deserialization and Upload Risks.