XSS types, Razor's context-aware encoding and its gaps, rich-text sanitisation, front-end framework escapes, and CSP as defence in depth in ASP.NET Core.
XSS is when attacker-controlled input is rendered as script in your page, so it runs in your origin with the victim's session: it can read the DOM, call your API as the user and steal tokens kept in localStorage. Stored XSS is saved and served to other users; reflected echoes request input back; DOM-based happens entirely in client-side JavaScript (innerHTML, location.hash).
Razor's @ HTML-encodes by default, which stops most of it. The gaps are the escape hatches (Html.Raw, HtmlString, React's dangerouslySetInnerHTML, Blazor's MarkupString) and wrong contexts: HTML encoding doesn't make a value safe inside a <script> block or an href="javascript:...". Rich text needs an allow-list sanitiser. A CSP with nonces is the safety net, not the fix.
> "XSS is any bug where data I meant to display gets interpreted as code by the browser. Because that script runs on my origin, the same-origin policy is no help: it can read the page, call my API with the user's cookies, and grab anything in localStorage, which is one reason I don't keep tokens there. Stored XSS is the worst because one comment field can hit every user; reflected comes from the URL or form and needs a crafted link; DOM-based never touches the server, it's client code writing location.hash into innerHTML.
>
> The core defence is output encoding in the right context, and Razor does that by default: @Model.Name goes through HtmlEncoder, so `
Checks that the candidate understands XSS as an output-encoding problem with context, knows Razor's guarantees and escape hatches, and uses CSP as defence in depth.
Green flags
Red flags
<script>attacker input --> stored/reflected --> your HTML --> victim's browser
|
runs as https://app.example.com.au
- reads the DOM: PII, CSRF tokens
- reads localStorage / sessionStorage
- fetch('/api/...') with the user's cookies
- rewrites the page (fake login form)
HttpOnly cookies stop script reading the session cookie, but script can still use it by making requests from the victim's browser. That is why XSS defeats CSRF protection too: the script can read the antiforgery token from the page.
| Storage | Readable by injected script? | Sent automatically? | Notes |
|---|---|---|---|
localStorage |
Yes | No | Persists across tabs and restarts: worst place for tokens |
sessionStorage |
Yes | No | Per tab, cleared on close, still fully exposed to XSS |
| In-memory JS variable | Yes (while page lives) | No | Shorter exposure, lost on refresh |
| HttpOnly cookie | No | Yes | Script can't exfiltrate it, but can ride it (needs CSRF defences) |
This is the main reason the BFF pattern keeps tokens server-side and gives the browser only an HttpOnly session cookie.
Razor compiles @expr to Write(expr), which calls HtmlEncoder.Default.Encode for strings (and for IHtmlContent writes as-is). The default encoder encodes <, >, &, ", ' and every character outside Basic Latin, which is also why non-English text shows up as &#x...; unless you widen WebEncoderOptions.TextEncoderSettings. Html.Raw, new HtmlString(...) and MarkupString in Blazor mark content as already safe.
HTML encoding turns < into <, which is right in an HTML text node. Inside `` can break out. In an href, javascript:alert(1) contains no characters that HTML encoding changes. So you need the encoder for the context (JavaScriptEncoder, UrlEncoder) or, better, avoid putting data in those contexts: serialise to JSON with JsonSerializer (which escapes <, >, & and quotes by default) into a data- attribute or a `
Html.Raw to render user content 'because it has formatting'. Why it is wrong: any markup, including event handlers, runs in your origin. Instead: sanitise with an allow-list library on save, or render as plain text.<script> blocks with Razor. Why it is wrong: HTML encoding isn't JavaScript encoding; quotes and </script> can break out. Instead: serialise to JSON in a data- attribute and read it from script.href without checking the scheme. Why it is wrong: javascript: URLs survive HTML encoding. Instead: allow only https: (and maybe mailto:) after Uri.TryCreate.<script>. Why it is wrong: there are countless vectors (<svg onload>, encoded variants) and browsers parse leniently. Instead: encode on output; sanitise rich text with a real parser.dangerouslySetInnerHTML, MarkupString, innerHTML and URL props bypass escaping. Instead: lint for them and review every use.unsafe-inline or broad host allow-lists is easily bypassed, and not all browsers enforce everything. Instead: fix encoding; use a nonce-based CSP as defence in depth.localStorage in an app with any XSS risk. Why it is wrong: one XSS exfiltrates every token. Instead: use HttpOnly cookies via a BFF.The senior framing: XSS is an output problem, solved per context, backed by CSP and by process. Input validation helps (reject a URL that isn't https:), but you can't validate free text into safety, and data reaches pages through paths you didn't plan (imports, admin tools, other services). I want a codebase where unsafe sinks are rare, greppable and reviewed (Html.Raw, HtmlString, MarkupString, dangerouslySetInnerHTML, bypassSecurityTrust*, innerHTML), and a lifecycle that catches the rest: lint rules and analysers in CI, XSS cases in security tests, a DAST scan in the pipeline, and developers who know why the rules exist.
| Control | When it fits | Cost | When not to rely on it alone |
|---|---|---|---|
| Context-aware output encoding | Always | Free with Razor/React/Angular | Never optional |
| Allow-list HTML sanitiser | Rich text from users | CPU per save, library updates | Plain-text fields (just encode) |
Nonce-based CSP + strict-dynamic |
Server-rendered apps, SPAs with a BFF | Removing inline scripts, nonce plumbing, auditing what trusted scripts load | As the only defence |
| Trusted Types | Large SPAs with DOM-XSS risk | Refactoring sinks; Chromium-centric | Small apps |
| HttpOnly session cookies, no tokens in Web Storage | Any browser auth | BFF or cookie auth | Stops theft, not actions |
Measure: CSP violation reports per day, the count of unsafe-sink usages tracked by a lint rule, and ZAP/Burp findings per release.
A refresh token lets a client get new short-lived access tokens without asking the user to sign in again. Because it is long-lived, it is the most valuable token to steal.
HttpOnly, Secure, SameSite cookie.The trade-off: a BFF adds a server hop and session state, in exchange for tokens that never reach the browser.
After a successful login the app calls HttpContext.SignInAsync: the cookie handler serialises the ClaimsPrincipal into an authentication ticket, encrypts and signs it with Data Protection, and sends it as a cookie. On each request the handler decrypts the cookie and rebuilds HttpContext.User, with no database call.
HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).ExpireTimeSpan (default 14 days) with sliding expiration that reissues the cookie once half the window has passed; IsPersistent decides whether it survives closing the browser.The trade-off: a self-contained cookie is fast and stateless, but you can't revoke it without extra checks or a server-side ticket store.
How to tell it (STAR)
**S:** At [company] a pen test found stored XSS in our support portal: a customer's 'website' link ran script when an agent opened the ticket. **T:** I owned the fix and needed to make sure it wasn't the only one before [the renewal]. **A:** I reproduced it, saw that `javascript:` URLs survive HTML encoding, and searched the codebase for every raw or URL sink, finding [number] more. We cleaned the stored data, validated URL schemes, replaced `Html.Raw` with an allow-list sanitiser and rolled out a nonce-based CSP, report-only first. **R:** The retest came back clean, CSP reports dropped to [near zero] after we moved [number] inline scripts, and CI now blocks new raw sinks without review.
Last updated 23 Nov 2026.