XSS, CSRF, Clickjacking, CORS, and Open Redirect
Trace untrusted data from sources to dangerous sinks, exploit and fix XSS, then close the browser-side gaps that enable request forgery, framing, cross-origin reads, and redirect abuse.
By the end, you’ll be able to…
- Identify sources and sinks and distinguish reflected, stored, and DOM-based cross-site scripting.
- Apply context-aware output encoding, sanitisation, and Content Security Policy as independent layers.
- Explain and test CSRF, clickjacking, CORS misconfiguration, and open redirects with safe lab payloads.
- Recommend fixes that address the root cause rather than blocking a single payload string.
01Sources, Sinks, and Three Kinds of XSS
Cross-site scripting happens when untrusted data reaches a browser context where it is interpreted as code. The data comes from a source: a query string, a URL fragment, a form field, a cookie, a database record, an API response, or a postMessage event. It becomes dangerous at a sink: an HTML parser assignment, an attribute write, a script evaluation, or a URL scheme that executes. Reflected XSS bounces immediately from the request into the response. Stored XSS saves the payload and serves it to later visitors. DOM-based XSS never involves the server's HTML; client-side JavaScript copies a source into a sink.
A search page that prints the query back without encoding is reflected XSS. A comment field that stores markup and renders it to every reader is stored XSS. A page that reads location.hash and assigns it to innerHTML is DOM XSS. The three have different delivery paths but the same underlying failure: data crossed into an executable context without the correct treatment.
Use payloads that prove execution without causing harm. In a local lab, alert(document.domain) shows which origin executed the script and demonstrates that the same-origin boundary has been crossed. An image with an onerror handler proves execution when script tags are filtered. Never use a payload that reads cookies, sends data to an external host, or changes state, even in a lab, because it normalises harmful behaviour and may leak real session material if the scope is wrong.
SAFE LAB PROOFS (local target, alert only)HTML body context: <script>alert(document.domain)</script>Double-quoted attribute breakout: "><svg onload=alert(1)>Single-quoted attribute breakout: ' onmouseover='alert(1)URL attribute context: javascript:alert(document.domain)DOM sink test, after the # in a lab page that uses innerHTML: #<img src=x onerror=alert(1)>Template literal injection inside a script block: ${alert(1)}Why these are acceptable proofs:- alert shows the origin and stops.- No cookie access, no network exfiltration, no state change.- If the payload is sanitised, the alert does not appear and the page renders text.02Contexts and Encoding: The Only Reliable Fix
HTML is not one context. Text between tags, a quoted attribute value, an unquoted attribute, a URL, a JavaScript string, a CSS block, and a JSON document each have different escaping rules. Encoding that is correct for HTML text can be wrong inside a JavaScript string, and URL encoding does not protect an HTML attribute. A templating engine with automatic escaping handles the common cases, but you must know which context it assumes and where it is bypassed by raw output.
The safe pattern is to keep data out of executable syntax entirely. Use textContent instead of innerHTML for text. Create elements with createElement and set attributes explicitly. Put dynamic URLs through a scheme allowlist that permits only http and https. Serialise JSON with a library and escape the characters that can terminate a script block. For rich text, sanitise with a maintained allowlist-based library such as DOMPurify, then still encode at the final sink. Sanitisation is for markup that must remain markup; encoding is for everything else.
Dangerous sinks are worth memorising: innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, new Function, string arguments to setTimeout, jQuery html and append, and framework escape hatches such as dangerouslySetInnerHTML. Safe sinks include textContent, createTextNode, and value assignment for form fields. The presence of a dangerous sink is not automatically a bug; the bug is passing untrusted data into it without a proven sanitiser. Review every raw HTML escape hatch in a codebase and require a justification.
03Impact, Cookie Theft, and Content Security Policy
The impact of XSS depends on what the vulnerable origin can do. A script running in a banking session can read the DOM, submit forms, change settings, and call authenticated APIs as the victim. If the session cookie lacks HttpOnly, the script can read document.cookie and send it elsewhere, which turns a temporary script execution into durable account takeover. Even with HttpOnly, the script can act inside the page: this is session riding, and it is often enough to transfer money or change an email address.
Content Security Policy is a second layer that restricts which scripts may execute. A strict policy uses a per-request nonce or a hash for each legitimate inline script, sets script-src to the application's own origin, disables object-src, and locks base-uri so an injected base tag cannot redirect relative script URLs. The strict-dynamic keyword lets nonce-approved scripts load further scripts while blocking injected inline handlers. Start with Content-Security-Policy-Report-Only, collect violation reports, fix legitimate sources, then enforce. A policy containing unsafe-inline or a broad wildcard provides little protection.
CSP does not repair an encoding bug. It raises the cost of exploitation and blocks entire payload families, but injected data can still break the page, exfiltrate through allowed channels, and abuse DOM gadgets. Trusted Types adds another layer by forcing dangerous sinks through a policy that sanitises input. Report violations to a monitored endpoint, because a burst of CSP reports is often the first sign that an XSS filter is being probed.
HTTP/1.1 200 OKContent-Type: text/html; charset=UTF-8Content-Security-Policy: default-src 'self'; script-src 'nonce-r4nd0mB64' 'strict-dynamic'; style-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-reportSet-Cookie: session=...; Secure; HttpOnly; SameSite=Lax; Path=/X-Content-Type-Options: nosniffReferrer-Policy: strict-origin-when-cross-originX-Frame-Options: DENY04CSRF: Making the Browser Send the Request
Cross-site request forgery abuses the fact that browsers attach cookies to requests regardless of which site initiated them. An attacker page submits a form to https://bank.example/transfer with the victim's session cookie attached, and the server sees a valid authenticated request. The attacker cannot read the response because of the same-origin policy, but reading is unnecessary when the goal is a state change. Classic targets are email changes, password changes, fund transfers, and administrative actions performed with a single POST.
Defences work by proving that the request came from the application's own interface. A synchroniser token is a random value stored in the session and embedded in each state-changing form; the server compares the submitted token with the stored one. Double-submit cookies store the token in a cookie and require the same value in a header or body, which works when the cookie is scoped correctly. SameSite=Lax or Strict stops most cross-site cookie attachment, but it is a browser default rather than a complete control and must be combined with tokens for sensitive actions. Check the Origin and Sec-Fetch-Site headers as additional signals.
CSRF protection must cover every state-changing route, including JSON APIs, GraphQL mutations, and logout. A JSON endpoint that only accepts application/json is harder to forge from a simple HTML form, but not impossible when CORS is permissive. Do not accept state changes on GET. Re-authenticate for high-risk actions such as changing a password or adding a payment method. Invalidate the old token after use if the flow is sensitive, and never put a CSRF token in a URL where it can leak through logs and referrers.
<!-- Hosted on an attacker-controlled origin in an isolated lab. --><!-- The browser attaches the victim's cookies to this cross-site POST. --><form action="http://127.0.0.1:3000/account/email" method="POST"> <input type="hidden" name="email" value="attacker@lab.test"> <input type="hidden" name="confirm" value="1"> <input type="submit" value="Claim your prize"></form><!-- Defences on the server side: 1. Require a per-session anti-CSRF token in the body or a header. 2. Set SameSite=Lax or Strict on the session cookie. 3. Reject requests whose Origin is not the application origin. 4. Require the current password for email and password changes. 5. Never perform state changes on GET requests. -->05Clickjacking and Frame Controls
Clickjacking loads the target application in an iframe and overlays it with transparent or disguised elements, so a victim believes they are clicking one thing while actually clicking another. A lab demonstration frames a page containing a delete button, positions the iframe under a decoy button, and shows that the click reaches the real control. Variants include cursorjacking, where the visible pointer is displaced, and multi-step framing that walks a user through a confirmation dialog.
The defence is to control who may frame the page. X-Frame-Options: DENY blocks all framing; SAMEORIGIN allows only the same origin. The modern control is Content-Security-Policy frame-ancestors, which supports an explicit list of origins and takes precedence where both are present. frame-ancestors 'none' is appropriate for most authenticated applications. JavaScript frame-busting is not a defence: it can be bypassed with sandboxing and double framing, and it breaks legitimate embedding.
Framing also matters for same-origin content. An attacker who can inject an iframe into a page may be able to combine it with other UI redress techniques, and a framed page that reads its own parent can leak data across widgets. Audit any feature that intentionally allows embedding, such as a checkout widget, and scope frame-ancestors to the exact partner origins rather than a wildcard.
HTTP/1.1 200 OKContent-Security-Policy: frame-ancestors 'none'X-Frame-Options: DENY# If embedding is a genuine product requirement, name the partners:Content-Security-Policy: frame-ancestors https://shop.partner.example https://checkout.partner.example# Do not rely on JavaScript frame busting:# if (window.top !== window.self) { window.top.location = window.self.location; }# It can be defeated by a sandboxed iframe and breaks accessibility tooling.06CORS Misconfiguration and Open Redirects
CORS is how a server tells the browser that a different origin may read its responses. The critical headers are Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Access-Control-Allow-Methods, and Access-Control-Allow-Headers. A wildcard origin is acceptable for public, unauthenticated data. It is not acceptable with credentials, and browsers reject that combination. The dangerous pattern is a server that reflects any Origin header and also sets Allow-Credentials: true, because then any attacker page can read authenticated API responses.
Common bypasses include trusting a null origin, which sandboxed iframes and some local files produce; matching a prefix with a regular expression, so https://app.example.com.evil.test passes; and trusting every subdomain, so an XSS on a marketing site becomes an API data leak. Test with an Origin you control in a local lab and inspect whether the response echoes it, whether credentials are allowed, and whether the preflight permits the method and headers you need. The fix is an exact allowlist, a Vary: Origin header for caches, credentials only where required, and server-side authorisation that never relies on CORS.
An open redirect lets an attacker turn a trusted link into a bounce to another site. Parameters such as next, return, redirect_uri, and continue are common. Bypasses include protocol-relative URLs (//evil.test), userinfo tricks (https://trusted.example@evil.test), backslash variants, encoded schemes, and paths that a weak prefix check accepts (https://trusted.example.evil.test). The impact is phishing that carries a trusted domain, and chaining with OAuth or SSO where a redirect parameter is trusted during token delivery. Fix by allowing only relative paths, or by matching an exact host allowlist after parsing the URL, and by showing an interstitial when leaving the site.
OPEN REDIRECT PAYLOADS (lab only) /login?next=https://evil.test /login?next=//evil.test /login?next=https://trusted.example@evil.test /login?next=https://trusted.example.evil.test /login?next=/\evil.test /login?next=%2F%2Fevil.testSAFE HANDLING Parse with a URL library. Accept only a relative path that starts with "/" and does not start with "//" or "/\". Otherwise redirect to "/". For absolute destinations, compare the parsed host to an exact allowlist. Show an interstitial for external destinations.CORS RESPONSE TO REVIEW Access-Control-Allow-Origin: https://evil.test <-- reflected Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: GET, POST, DELETE This lets an attacker origin read authenticated responses. Replace the reflection with an exact allowlist and remove credentials if not needed.07Testing the Browser Attack Surface
Test XSS by context, not by payload list. For every reflection, identify where the value lands: HTML text, an attribute, a script block, a URL, or a DOM sink. Then choose the smallest proof for that context. Use a browser with the CSP report console open, and confirm whether the payload executes or is blocked. Test stored values after a reload and from a second account, because storage and rendering may use different code paths.
Test CSRF with a second browser profile or an isolated container that holds the victim session, then submit a cross-site form from a different origin. Confirm the action succeeds without a token and fails with an invalid token. Test SameSite behaviour explicitly rather than assuming it. For clickjacking, load the target in an iframe and check the console for refusal. For CORS, send an Origin header from a lab host and compare the response with and without credentials. For redirects, try relative, protocol-relative, userinfo, and suffix tricks, and verify where the browser actually lands.
Document each finding with the exact request, the browser behaviour, and the missing control. The fix must name the sink or the header, not just the payload that was blocked. A report that says 'filter the script tag' invites a bypass; a report that says 'encode at the HTML text sink and add a nonce-based CSP' gives the developer a durable change.
The ideas worth keeping.
- XSS is a source-to-sink problem; the fix depends on the exact output context, not on a blocklist of tags.
- HttpOnly and CSP reduce impact, but safe DOM APIs and correct encoding remain the primary controls.
- CSRF, clickjacking, and permissive CORS all abuse browser trust; tokens, SameSite, frame-ancestors, and exact origin allowlists close them.
- Open redirects are phishing primitives and become far worse when chained with OAuth or SSO flows.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Fix a DOM-based search reflection
A lab page runs const q = new URLSearchParams(location.search).get('q'); document.getElementById('results').innerHTML = 'Results for ' + q;. Craft a safe proof of execution, explain why the server cannot fix this, and rewrite the code.
Explore a worked solution
A safe proof is ?q=<img src=x onerror=alert(document.domain)>, which executes because the value reaches innerHTML. The server never sees the fragment or the DOM assignment, so server-side filtering cannot reliably fix it; the sink is in client code. Replace innerHTML with textContent and build any markup with createElement. If highlighting is required, escape the value and insert it as text nodes, or sanitise with a maintained allowlist library. Add a strict CSP with a nonce and no unsafe-inline as defence in depth, and test with the payload plus an encoded variant.DOM XSS is fixed at the client sink. Encoding must match the sink, and CSP limits the damage but does not replace safe DOM APIs.
Exercise 2: Review a CORS and redirect chain
An API reflects any Origin and allows credentials. The login page accepts ?next= and redirects after authentication. Explain how the two issues combine, what an attacker can read, and how to fix both.
Explore a worked solution
The open redirect gives the attacker a trusted link that lands on the real login page and then bounces to an attacker site after authentication, which is convincing phishing and can leak tokens if they appear in the URL. The CORS reflection lets an attacker origin make credentialed requests to the API and read the responses, so any authenticated data the API returns is exposed. Fix CORS with an exact origin allowlist, credentials only for those origins, a Vary: Origin header, and no trust in null or suffix matches. Fix the redirect by accepting only relative paths or an exact host allowlist, and show an interstitial for external destinations. Add server-side authorisation and never treat CORS as an access control.Each issue is serious alone; together they enable convincing phishing and direct data theft. Fixes must be exact-match and server-enforced.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.