📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is cross-site scripting (XSS)? Explain stored, reflected and DOM-based XSS, how Razor's automatic encoding protects you and where it doesn't (Html.Raw, JavaScript and URL contexts), how React and Blazor compare, and how a Content Security Policy limits the damage.

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.

Mid-Level Security Intermediate aspnet-core csp razor react security xss

🎯 Key points

  • XSS = attacker-controlled script running in your origin: it can read the DOM and PII on the page, call your APIs as the user and rewrite the UI
  • Stored (saved and served to others), reflected (echoed from the request), DOM-based (client-side sink such as innerHTML)
  • Razor @ HTML-encodes via HtmlEncoder; Html.Raw and HtmlString bypass it
  • HTML encoding is wrong for JavaScript and URL contexts: javascript: hrefs, inline script variables
  • Rich text needs an allow-list sanitiser (e.g. HtmlSanitizer), never regex blacklists
  • React/Blazor escape by default and Angular sanitises bound HTML; dangerouslySetInnerHTML, MarkupString and bypassSecurityTrust* are the escape hatches
  • localStorage and sessionStorage are readable by any script in the origin; HttpOnly cookies are not, but script can still use them
  • Nonce-based CSP blocks injected scripts; 'strict-dynamic' extends trust to scripts that nonced scripts load

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

> "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 `

🔍 What the interviewer is checking

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

  • Distinguishes stored, reflected and DOM-based with sinks
  • Knows HTML encoding doesn't cover JavaScript or URL contexts
  • Uses an allow-list sanitiser for rich text
  • Describes a nonce-based CSP rolled out in report-only mode

Red flags

  • 'We validate input, so we're safe from XSS'
  • Thinks HttpOnly cookies make XSS harmless
  • Relies on regex filtering of <script>

📚 Learn in depth

1. Why XSS is so powerful

attacker input --&gt; stored/reflected --&gt; your HTML --&gt; 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.

2. Where secrets live and what XSS can reach

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.

3. How Razor encodes

Razor compiles @expr to Write(expr), which calls HtmlEncoder.Default.Encode for strings (and for IHtmlContent writes as-is). The default encoder encodes &lt;, &gt;, &amp;, ", ' and every character outside Basic Latin, which is also why non-English text shows up as &amp;#x...; unless you widen WebEncoderOptions.TextEncoderSettings. Html.Raw, new HtmlString(...) and MarkupString in Blazor mark content as already safe.

4. The context problem

HTML encoding turns &lt; into &lt;, 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 &lt;, &gt;, &amp; and quotes by default) into a data- attribute or a `

💻 Code

Vulnerable and fixed Razor, a safe way to pass data to JavaScript, server-side sanitisation for rich text, and URL scheme validation. ```cshtml @* VULNERABLE: user content rendered as markup, and data written into a script block *@ website @* FIXED *@ @* sanitised on save, see below *@ @if (Model.WebsiteIsHttps) { website } ``` ```csharp using Ganss.Xss; namespace Portal.Comments; public sealed class CommentSanitiser { private readonly HtmlSanitizer _sanitizer = new(); public CommentSanitiser() { // Allow-list: start from the defaults and remove what you don't need _sanitizer.AllowedTags.Clear(); foreach (var tag in new[] { "p", "br", "b", "i", "em", "strong", "ul", "ol", "li", "a" }) _sanitizer.AllowedTags.Add(tag); _sanitizer.AllowedSchemes.Clear(); _sanitizer.AllowedSchemes.Add("https"); // no javascript:, data: } public string Sanitise(string html) => _sanitizer.Sanitize(html); } public static class UrlRules { public static bool IsSafeHttpsUrl(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps; } ```

⚠ Common mistakes

  • Mistake: Using 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.
  • Mistake: Writing model values into inline <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.
  • Mistake: Rendering user-supplied URLs in href without checking the scheme. Why it is wrong: javascript: URLs survive HTML encoding. Instead: allow only https: (and maybe mailto:) after Uri.TryCreate.
  • Mistake: Filtering input with a regex blacklist for <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.
  • Mistake: Assuming React or Blazor makes XSS impossible. Why it is wrong: dangerouslySetInnerHTML, MarkupString, innerHTML and URL props bypass escaping. Instead: lint for them and review every use.
  • Mistake: Treating CSP as the fix. Why it is wrong: CSP with 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.
  • Mistake: Storing access tokens in localStorage in an app with any XSS risk. Why it is wrong: one XSS exfiltrates every token. Instead: use HttpOnly cookies via a BFF.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions tokens in localStorage being stolen by XSS Why: Checks they know where SPAs should keep tokens and why the BFF pattern is recommended
    How to answer

    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.

    • Rotation: every refresh returns a new refresh token and invalidates the old one. Reuse detection: if an old one is used again, someone has a copy, so the server revokes the whole token family.
    • Lifetimes: access tokens 5–15 minutes; refresh tokens bounded by an idle timeout and an absolute session limit.
    • Storage: in a SPA, anything JavaScript can read, XSS can steal. The BFF pattern keeps tokens on the server and gives the browser only an 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.

  2. When: Candidate mentions HttpOnly cookies Why: Checks they understand the cookie flags and what HttpOnly does and doesn't protect
    How to answer

    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.

    • Flags: HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).
    • Expiry: 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.
    • Keys: every instance must share the Data Protection key ring, or cookies issued by one server can't be read by another.

    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.

🛠 Real-world problems: how you handle them

Stored XSS through a user-supplied website link
Situation
A customer support portal built on ASP.NET Core MVC serves [number] agents and [number] customers. A pen test before [a contract renewal / IRAP assessment] reports stored XSS rated High.
Signals
Pen test report: payload in the profile 'website' field executes when an agent views the ticket. No alerts beforehand; no CSP in place; session cookie HttpOnly but antiforgery token readable in the page.
Investigation
Reproduced locally: the view rendered `<a href="@Model.Website">`, and a `javascript:` URL survived HTML encoding. Grepped the solution for `Html.Raw`, `HtmlString` and `href="@` and found [number] more risky sinks. Checked logs and the database for stored values starting with `javascript:` or containing `<` to assess exploitation; Burp Suite used to confirm each fix.
Resolution
Immediate: data fix to neutralise stored malicious values, scheme validation on input and conditional rendering on output, deployed same day. Long term: replaced `Html.Raw` uses with sanitised HTML via HtmlSanitizer, added a nonce-based CSP (report-only for two weeks, then enforced), and moved remaining inline scripts to nonced blocks.
Prevention
Roslyn analyser or grep check in CI failing on new `Html.Raw` without an approved suppression; CSP violation reports into Application Insights with an alert; XSS cases added to the ZAP scan in the pipeline; secure-coding checklist item for URL fields.

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.

↩ Usually asked after

More in Web Security

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me