ASP.NET Core MVC Intermediate

Preventing XSS and adding security headers

Cross-site scripting (XSS) lets an attacker run their JavaScript in your users' browsers. This lesson shows how Razor protects you by default, the few ways developers break that protection, and the security headers, including a Content Security Policy, that add a second layer.

Layers of XSS defence
  1. Razor encodingEvery @value is HTML-encoded
  2. Sanitize rich textAllow-list of tags when HTML is needed
  3. Safe JavaScripttextContent, no inline scripts
  4. Content Security PolicyBrowser refuses scripts you did not allow
  5. HttpOnly cookiesScripts cannot read the session cookie

How XSS happens

If a comment containing <script>steal()</script> is stored and later written into a page as raw HTML, every visitor runs that script. It can read the page, act as the user and send data elsewhere.

Razor HTML-encodes everything you write with @, so @comment.Text shows the tags as text instead of running them. Most XSS bugs in MVC apps come from switching that off.

Where protection gets broken

  • @Html.Raw(userText) writes HTML without encoding. Only use it for HTML you generated or sanitized.
  • Putting user data inside a <script> block or an onclick attribute. Pass data with data-* attributes or JSON from an endpoint instead.
  • Setting innerHTML in JavaScript with values from JSON. Use textContent.
  • href="@userUrl" can be a javascript: URL; allow only http and https.
  • If users need rich text, sanitize it on save with a library such as HtmlSanitizer and an allow-list of tags.

Security headers

Headers tell the browser to apply extra protections. A Content Security Policy is the strongest: it blocks inline scripts and scripts from unknown hosts, so even an injected <script> tag will not run.

C#
app.Use(async (context, next) =>
{
    var h = context.Response.Headers;
    h["Content-Security-Policy"] =
        "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; " +
        "object-src 'none'; base-uri 'self'; frame-ancestors 'none'";
    h["X-Content-Type-Options"] = "nosniff";
    h["Referrer-Policy"] = "strict-origin-when-cross-origin";
    h["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()";
    await next();
});

app.UseHsts();             // production: browsers use HTTPS only
app.UseHttpsRedirection();

Making CSP work with your views

  • Move inline <script> blocks and onclick handlers into .js files.
  • Move style="..." attributes into CSS classes.
  • If you must keep an inline script, use a per-request nonce instead of 'unsafe-inline'.
  • Start with Content-Security-Policy-Report-Only to find violations before enforcing.
  • Cookies: keep HttpOnly, Secure and SameSite on auth cookies so scripts cannot read them.

Interview question

How does Razor protect against XSS, and how can a developer accidentally bypass it?

Razor HTML-encodes every value written with @, so characters like < and > appear as text instead of creating tags. Developers bypass it with Html.Raw or HtmlString on untrusted data, by writing user values into inline scripts or event attributes, by allowing javascript: URLs in links, or by setting innerHTML in client-side code. A Content Security Policy is a good second line of defence.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.