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

📚 Interview question

Which security headers should an ASP.NET Core app send, and how do you roll out a Content Security Policy safely? Explain what each header protects against, how you set them in middleware, how CSP nonces work with Razor, and why you start in report-only mode.

The security headers that matter for ASP.NET Core apps and APIs, setting them in middleware, nonce-based CSP with Razor, and a report-only rollout.

Intermediate Theory Intermediate aspnet-core csp hsts middleware security security-headers

🎯 Key points

  • Core set: Strict-Transport-Security, Content-Security-Policy, X-Content-Type-Options: nosniff, Referrer-Policy, Permissions-Policy
  • frame-ancestors (plus X-Frame-Options for old clients) against clickjacking
  • X-XSS-Protection is unsupported in modern browsers: send 0 or omit; remove Server and X-Powered-By
  • Nonce-based script-src with 'strict-dynamic'; 'unsafe-inline' and https: are only fallbacks that nonce-aware browsers ignore
  • A fresh cryptographically random nonce per response, passed to Razor via HttpContext.Items
  • Roll out with Content-Security-Policy-Report-Only; report via report-to + Reporting-Endpoints (and report-uri for older browsers); log reports bounded and rate-limited
  • APIs need a minimal set: default-src 'none'; frame-ancestors 'none', nosniff, HSTS
  • Set headers once in middleware registered early with OnStarting (covers errors and static files) or a Front Door rule, and assert them in integration tests

⏱ 30-second answer

Security headers tell the browser to apply protections for your origin. The set worth knowing: Strict-Transport-Security (HTTPS only), Content-Security-Policy (which scripts, frames and resources may load), X-Content-Type-Options: nosniff (no MIME sniffing), Referrer-Policy (don't leak full URLs to other sites), Permissions-Policy (switch off camera, geolocation and similar) and frame-ancestors / X-Frame-Options against clickjacking. X-XSS-Protection is obsolete.

In ASP.NET Core, set them once in middleware or at the edge. For CSP, generate a per-response nonce, put it on your <script> tags, and use script-src 'nonce-...' 'strict-dynamic'. Roll it out with Content-Security-Policy-Report-Only first, because an enforced policy that's wrong breaks the site. The trade-off: CSP is powerful defence in depth but needs inline scripts removed.

🗣 Full answer (senior)

How I would answer this in an interview

"Security headers are instructions to the browser, so they protect users of a browser app. They don't fix bugs in my code, but they shrink what an attacker can do with one. The ones I always send are HSTS so the browser sticks to HTTPS; X-Content-Type-Options: nosniff so a user-uploaded file served as text/plain can't be sniffed into script; Referrer-Policy: strict-origin-when-cross-origin so tokens or ids in my URLs don't leak to third parties; a Permissions-Policy that turns off features I don't use; and a Content Security Policy, which carries the most weight: it says which scripts may run and, through frame-ancestors, who may frame me.

In ASP.NET Core I add them in one small middleware registered early, using OnStarting so they land on every response, including errors and static files, or I use a library such as NetEscapades.AspNetCore.SecurityHeaders. For CSP I avoid host allow-lists, which are easy to bypass through a JSONP endpoint or a CDN that hosts anything. Instead I generate a random nonce per response, store it in HttpContext.Items, write it on every legitimate <script> tag in the layout, and send script-src 'nonce-xyz' 'strict-dynamic'. Injected markup can't know the nonce, so it doesn't run.

The mistake I see is shipping an enforced CSP on day one and breaking checkout because of an inline handler or an analytics tag. I start with Content-Security-Policy-Report-Only and a reporting endpoint, watch a week or two of reports, fix the legitimate violations, then switch the header name to enforce. Headers are cheap; a CSP that breaks production gets turned off and never comes back."


The headers

Header Protects against Typical value
Strict-Transport-Security SSL stripping, downgrade max-age=31536000; includeSubDomains
Content-Security-Policy XSS impact, clickjacking, data exfiltration script-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
X-Content-Type-Options MIME sniffing into script nosniff
Referrer-Policy Leaking paths and query strings strict-origin-when-cross-origin (or no-referrer)
Permissions-Policy Abuse of powerful browser features camera=(), microphone=(), geolocation=()
X-Frame-Options Clickjacking in old browsers DENY
Cross-Origin-Opener-Policy Cross-window attacks, XS-Leaks same-origin

Headers to drop or neutralise

Header Why
X-XSS-Protection Removed from modern browsers; the old filter could introduce bugs. Send 0 or omit
Server: Kestrel, X-Powered-By Free fingerprinting; set AddServerHeader = false

Browser app vs API

Browser app JSON API
CSP Full nonce-based policy default-src 'none'; frame-ancestors 'none'
HSTS, nosniff Yes Yes
Permissions-Policy, Referrer-Policy Yes Optional

Production example

On a customer portal, two weeks of report-only CSP produced about 1,200 reports a day: 90% from browser extensions (ignored), the rest from three inline onclick handlers and an old analytics snippet. Moving those to nonced scripts took two days; after enforcing, reports dropped to a few dozen a day, almost all extension noise, and the site's security-header scan went from an F to an A.

🔍 What the interviewer is checking

Checks that the candidate knows which headers matter and why, can implement them once in ASP.NET Core, and understands a safe nonce-based CSP rollout.

Green flags

  • Explains what each header protects against, not just its name
  • Uses nonces with 'strict-dynamic' rather than host allow-lists
  • Rolls out CSP in report-only mode with a reporting endpoint
  • Sets headers in one place and tests them

Red flags

  • Recommends X-XSS-Protection: 1 as protection
  • Uses 'unsafe-inline' as the main policy
  • Thinks headers alone fix XSS

📚 Learn in depth

1. How browsers apply headers

Headers are per response. The browser enforces CSP for the document it applies to; HSTS is remembered per host; nosniff applies to each resource. That's why setting headers only on HTML pages misses uploads, errors and static files.

request -> middleware (OnStarting registers headers) -> endpoint/static files/exception handler
        <- response leaves with headers whatever produced it

2. CSP building blocks

  • Fetch directives limit where resources load from: default-src, script-src, style-src, img-src, connect-src, font-src.
  • Document directives: base-uri (stops <base> hijacking), object-src 'none' (no plugins).
  • Navigation directives: frame-ancestors (who may frame you), form-action (where forms may post).
  • Reporting: the report-to directive with a Reporting-Endpoints header (current), and the older report-uri, still widely supported, so many sites send both.

3. Why nonces beat allow-lists

Host allow-lists (script-src https://cdn.example.com) are bypassed if any allowed host serves attacker-controllable script (JSONP endpoints, old library versions, user content on a shared CDN). A nonce is a random value generated per response; only tags carrying it run. With 'strict-dynamic', scripts loaded by a nonced script are trusted too, which makes bundlers and loaders work, and browsers that support it ignore host lists and 'unsafe-inline' (kept only as fallbacks for very old browsers).

Requirements: at least 128 bits from a CSPRNG, new for every response, never cached in shared HTML (a cached page with a fixed nonce defeats the point).

4. Nonces in ASP.NET Core

  1. Middleware generates the nonce: Convert.ToBase64String(RandomNumberGenerator.GetBytes(16)).
  2. Store it in HttpContext.Items["csp-nonce"].
  3. The layout writes nonce="@Context.Items["csp-nonce"]" on each <script>; a tag helper makes this tidy.
  4. The header is built in OnStarting with the same value.

Inline event handlers (onclick=...) and javascript: URLs can't carry nonces, so they must move into script files or nonced blocks.

5. Rollout

week 0  : Content-Security-Policy-Report-Only + reporting endpoint
week 1-2: triage reports (ignore extensions: chrome-extension://, moz-extension://)
          fix inline scripts, add nonces, adjust connect-src/img-src
week 3  : switch to Content-Security-Policy (enforce), keep reporting on
ongoing : alert on report spikes after releases

6. Where to set headers

  • Middleware: version-controlled with the app, testable, aware of nonces.
  • Front Door / Application Gateway rules: central, but can't do per-response nonces.
  • A common split: static headers at the edge, CSP with nonces in the app. Never both for the same header, or browsers see duplicates.

Try it yourself

  1. Add the middleware below to a sample app and check the headers with curl -I and a scanner such as securityheaders.com (on a non-production host).
  2. Add a report-only CSP and an inline onclick; read the violation in the console and your reporting endpoint.
  3. Move the handler into a nonced script and confirm the violation disappears.
  4. Serve an uploaded .txt containing HTML with and without nosniff and compare browser behaviour.
  5. Write an integration test with WebApplicationFactory asserting each header on a page, a static file and an error response.

💻 Code

One middleware that sets the security headers on every response, with a per-request CSP nonce available to Razor, plus a reporting endpoint and a test.

using System.Security.Cryptography;

namespace Portal.Security;

public sealed class SecurityHeadersMiddleware(RequestDelegate next, IHostEnvironment env)
{
    public const string NonceKey = "csp-nonce";

    public Task InvokeAsync(HttpContext context)
    {
        var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(16));
        context.Items[NonceKey] = nonce;

        context.Response.OnStarting(() =>
        {
            var h = context.Response.Headers;
            var csp = $"script-src 'nonce-{nonce}' 'strict-dynamic' https: 'unsafe-inline'; " +
                      "object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'; " +
                      "report-uri /csp-reports";
            // Report-only until the reports are clean, then switch the header name
            h[env.IsProduction() ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy"] = csp;
            h["X-Content-Type-Options"] = "nosniff";
            h["Referrer-Policy"] = "strict-origin-when-cross-origin";
            h["Permissions-Policy"] = "camera=(), microphone=(), geolocation=(), payment=()";
            h["X-Frame-Options"] = "DENY";
            h["Cross-Origin-Opener-Policy"] = "same-origin";
            h.Remove("X-Powered-By");
            return Task.CompletedTask;
        });

        return next(context);
    }
}
// Program.cs
builder.WebHost.ConfigureKestrel(o => o.AddServerHeader = false);

var app = builder.Build();
app.UseMiddleware<Portal.Security.SecurityHeadersMiddleware>();   // early, so errors get headers too
if (!app.Environment.IsDevelopment()) app.UseHsts();

app.MapPost("/csp-reports", async (HttpRequest req, ILogger<Program> log, CancellationToken ct) =>
{
    using var reader = new StreamReader(req.Body);
    var body = await reader.ReadToEndAsync(ct);
    if (body.Length < 8_192) log.LogWarning("CSP violation {Report}", body);   // bounded, structured
    return Results.NoContent();
}).DisableAntiforgery();
@* _Layout.cshtml: only scripts carrying the nonce run *@
<script nonce="@Context.Items[Portal.Security.SecurityHeadersMiddleware.NonceKey]" src="~/js/site.js" asp-append-version="true"></script>
// Integration test (xUnit + WebApplicationFactory)
[Fact]
public async Task Every_response_has_security_headers()
{
    using var client = factory.CreateClient();
    var response = await client.GetAsync("/does-not-exist");
    Assert.Equal("nosniff", response.Headers.GetValues("X-Content-Type-Options").Single());
    Assert.True(response.Headers.Contains("Content-Security-Policy")
             || response.Headers.Contains("Content-Security-Policy-Report-Only"));
}

⚠ Common mistakes

  • Mistake: Enforcing a strict CSP on day one. Why it is wrong: inline scripts and third-party tags break, and the policy gets removed under pressure. Instead: run report-only, fix violations, then enforce.
  • Mistake: Using 'unsafe-inline' or broad host allow-lists as the main policy. Why it is wrong: injected inline script runs, and allowed hosts often serve attacker-usable script. Instead: nonce-based script-src with 'strict-dynamic'.
  • Mistake: Reusing a nonce across responses or caching pages that contain it. Why it is wrong: a predictable nonce can be copied into injected markup. Instead: generate a fresh random nonce per response and don't cache personalised HTML in shared caches.
  • Mistake: Setting headers only on Razor pages. Why it is wrong: errors, static files and uploads go without nosniff and framing protection. Instead: register middleware early with OnStarting.
  • Mistake: Sending X-XSS-Protection: 1; mode=block. Why it is wrong: modern browsers removed the filter, and it caused vulnerabilities of its own. Instead: send 0 or omit it, and rely on CSP.
  • Mistake: Setting the same header at Front Door and in the app. Why it is wrong: duplicate CSP headers are combined, so the effective policy is stricter than either and often breaks pages. Instead: decide which layer owns each header.
  • Mistake: Treating headers as a fix for XSS. Why it is wrong: they reduce impact; the bug is still there. Instead: fix output encoding and use headers as defence in depth.

🏛 Senior insight: trade-offs

Senior engineers treat headers as policy as code: one owner, one place, tested, and rolled out with telemetry. The work in CSP is not the header string, it's refactoring the front end so every script is nonced or bundled. That's why it should be planned like a small project, with a report-only phase and owners for third-party tags.

Option When it fits Cost When not to
Custom middleware Most apps; nonce support needed Small code, tests Many apps needing one shared policy (use a library or the edge)
NetEscapades.AspNetCore.SecurityHeaders Teams wanting a maintained fluent API with nonce tag helpers A dependency Very custom per-route policies
Front Door / App Gateway rules Static headers across many apps Can't do nonces CSP with nonces
Report-only CSP Every first rollout and big front-end change Reporting endpoint, triage time As a permanent state

Measure: a scanner grade per environment, CSP violation report volume (spikes after releases mean a regression), and integration tests asserting headers on every response type.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says CSP stops XSS Why: Checks they know CSP is defence in depth and XSS is fixed with context-aware encoding
    How to 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.

  2. When: Candidate mentions HSTS Why: Checks depth on HSTS, preload and proxies
    How to answer

    TLS encrypts and authenticates the connection; HTTPS is HTTP over TLS. In ASP.NET Core, UseHttpsRedirection redirects plain-HTTP requests to HTTPS, and UseHsts adds the Strict-Transport-Security header so the browser refuses to use HTTP for that host for max-age (30 days by default), closing the first-request downgrade window after the first visit. Preload goes further: the domain is baked into browsers, so even the first visit is HTTPS — but it requires a year-long max-age, includeSubDomains, and is slow to undo.

    For APIs, don't depend on redirects: non-browser clients ignore HSTS and may already have sent a token over HTTP, so refuse HTTP instead. Behind a proxy, run UseForwardedHeaders first or the app thinks every request is HTTP and loops.

↩ Usually asked after

More in Web Security

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me