XSS, CSRF and CORS
Browsers run code from many websites side by side, and they automatically attach your cookies to requests. Three topics come from that: XSS (an attacker's script running inside your site), CSRF (another site making requests as you), and CORS (the rules for when one site may read another site's responses).
Cross-site scripting (XSS)
XSS happens when user-controlled text ends up in a page as HTML or JavaScript instead of as text. Then the attacker's script runs with the full power of your site: it can read the page, make requests as the user, steal tokens from localStorage, or rewrite the login form.
| Type | How the script gets in |
|---|---|
| Stored | Saved in the database (a comment, a username) and shown to every visitor |
| Reflected | Comes from the URL and is echoed into the response (/search?q=<script>…) |
| DOM-based | Client-side JavaScript writes untrusted data into the page (element.innerHTML = location.hash) |
In v1 the browser would create an <img> whose onerror handler sends the visitor's cookies to the attacker. In v2 the user sees the text itself, harmlessly.
Defences
- Let your framework escape output. React, Vue, Angular, Django templates, Jinja, Thymeleaf and EJS's
<%= %>escape by default. The danger is the escape hatches:dangerouslySetInnerHTML,v-html,|safe,<%- %>,innerHTML. - Escape for the right context. HTML text, HTML attributes, URLs, JavaScript strings and CSS each need different encoding. Never put untrusted data inside
<script>blocks or event-handler attributes. - Sanitise rich text (when users may submit HTML, such as in a blog editor) with a proven library such as DOMPurify, which keeps safe tags and removes scripts.
- Validate URLs: a link to
javascript:alert(1)is XSS. Allow onlyhttp:andhttps:. - Content Security Policy (CSP): a response header telling the browser which scripts may run. Even if an attacker injects a
<script>, the browser refuses it:
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'HttpOnlycookies so an XSS can't read session cookies (it can still act as the user, which is why escaping comes first).
helmet() sets a strict CSP and other protective headers in Express:
Cross-site request forgery (CSRF)
CSRF abuses the fact that browsers attach cookies to requests wherever they come from. While you're logged in to your bank, an evil page can submit a hidden form to the bank; your session cookie rides along.
CSRF only matters when authentication is automatic: cookies or HTTP Basic auth. APIs that require an Authorization: Bearer header are immune, because another site can't make your browser add that header.
Defences
SameSitecookies (Laxis the browser default for cookies without the attribute in Chrome, but set it explicitly). Cross-site POSTs then arrive without the session cookie.- CSRF tokens: a random token stored in the session and included in every form; the server rejects state-changing requests without the matching token. Django, Rails, Laravel and Spring Security do this automatically.
- Check where requests come from: modern browsers send
Sec-Fetch-SiteandOriginheaders.
CORS
The browser's same-origin policy stops JavaScript on one origin (scheme + host + port, like https://shop.example) from reading responses from another origin. That's what keeps evil.example from reading your webmail with your cookies.
But your own frontend at https://shop.example legitimately needs to call your API at https://api.shop.example. CORS (Cross-Origin Resource Sharing) lets the API say which origins are allowed, with response headers:
Access-Control-Allow-Origin: https://shop.example
Access-Control-Allow-Credentials: trueFor "non-simple" requests (JSON bodies, custom headers, PUT/DELETE), the browser first sends a preflight OPTIONS request asking for permission:
For evil.example there's no Access-Control-Allow-Origin header, so the browser blocks the real request.
Common CORS mistakes
Access-Control-Allow-Origin: *with credentials: browsers forbid it, so people "fix" it by reflecting anyOriginback, which lets every website make authenticated requests and read the answers. Use an allow-list.- Matching origins with sloppy patterns:
origin.endsWith('shop.example')also allowsevilshop.example. - Thinking CORS protects the server. It's enforced by browsers; curl and attackers' servers ignore it. CORS decides who may read responses in a browser, not who may call your API. Authentication and authorization do that.
Practice
- Add a third comment containing
"><script>alert(1)</script>and confirm v2 escapes it. - Configure helmet's CSP to also allow images from
https://images.shop.example. - Explain why an API that only accepts
Authorization: Bearertokens doesn't need CSRF tokens.
1.What is the most important defence against XSS?
2.Why does CSRF work at all?
3.What does CORS control?