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.
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.
"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: nosniffso a user-uploaded file served astext/plaincan't be sniffed into script;Referrer-Policy: strict-origin-when-cross-originso tokens or ids in my URLs don't leak to third parties; aPermissions-Policythat turns off features I don't use; and a Content Security Policy, which carries the most weight: it says which scripts may run and, throughframe-ancestors, who may frame me.In ASP.NET Core I add them in one small middleware registered early, using
OnStartingso 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 inHttpContext.Items, write it on every legitimate<script>tag in the layout, and sendscript-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-Onlyand 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."
| 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 |
| 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 | JSON API | |
|---|---|---|
| CSP | Full nonce-based policy | default-src 'none'; frame-ancestors 'none' |
| HSTS, nosniff | Yes | Yes |
| Permissions-Policy, Referrer-Policy | Yes | Optional |
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.
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
Red flags
X-XSS-Protection: 1 as protection'unsafe-inline' as the main policyHeaders 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
default-src, script-src, style-src, img-src, connect-src, font-src.base-uri (stops <base> hijacking), object-src 'none' (no plugins).frame-ancestors (who may frame you), form-action (where forms may post).report-to directive with a Reporting-Endpoints header (current), and the older report-uri, still widely supported, so many sites send both.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).
Convert.ToBase64String(RandomNumberGenerator.GetBytes(16)).HttpContext.Items["csp-nonce"].nonce="@Context.Items["csp-nonce"]" on each <script>; a tag helper makes this tidy.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.
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
curl -I and a scanner such as securityheaders.com (on a non-production host).onclick; read the violation in the console and your reporting endpoint..txt containing HTML with and without nosniff and compare browser behaviour.WebApplicationFactory asserting each header on a page, a static file and an error response.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"));
}
'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'.nosniff and framing protection. Instead: register middleware early with OnStarting.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.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.
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.
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.
Last updated 23 Nov 2026.