Security Headers and CSP in ASP.NET Core Without Breaking Your Site

Add CSP, HSTS and the other security headers with one small middleware, keep inline scripts working by hash, and roll it out without breaking pages.

R M Shahidul Islam Shahed · 4 min read

A handful of HTTP response headers close whole classes of attacks: script injection, clickjacking, MIME sniffing and leaky referrers. They cost nothing to send, yet most ASP.NET Core apps ship without them because a strict Content Security Policy has a reputation for breaking things. This guide adds them with one small middleware and shows how to roll out CSP safely. Examples target ASP.NET Core on .NET 10.

The headers and what they stop

Header Value Stops
Content-Security-Policy see below Injected scripts, styles and frames
Strict-Transport-Security max-age=31536000 Downgrade to plain HTTP
X-Content-Type-Options nosniff Browsers guessing a file is script
X-Frame-Options DENY Clickjacking in older browsers
Referrer-Policy strict-origin-when-cross-origin Full URLs (with tokens) leaking to other sites
Permissions-Policy camera=(), microphone=(), geolocation=() Embedded content using device features

One middleware for all of them

csharp
public sealed class SecurityHeadersMiddleware(RequestDelegate next)
{
    private static readonly string Csp = string.Join("; ",
        "default-src 'self'",
        "script-src 'self'",
        "style-src 'self'",
        "img-src 'self' data:",
        "font-src 'self'",
        "connect-src 'self'",
        "form-action 'self'",
        "frame-ancestors 'none'",
        "base-uri 'self'",
        "object-src 'none'");

    public Task InvokeAsync(HttpContext context)
    {
        context.Response.OnStarting(() =>
        {
            var h = context.Response.Headers;
            h.ContentSecurityPolicy = Csp;
            h.XContentTypeOptions = "nosniff";
            h.XFrameOptions = "DENY";
            h["Referrer-Policy"] = "strict-origin-when-cross-origin";
            h["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()";
            return Task.CompletedTask;
        });
        return next(context);
    }
}

Register it early so it covers error pages and static files too:

csharp
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/error");
    app.UseHsts();                      // Strict-Transport-Security
}

app.UseMiddleware<SecurityHeadersMiddleware>();
app.UseHttpsRedirection();
app.UseStaticFiles();

OnStarting sets the headers right before the response begins, so they're present even when a later component writes the response.

Reading the CSP

  • default-src 'self': anything not listed below may only load from your own origin.
  • script-src 'self': scripts only from your own files. Inline <script> blocks and onclick="" attributes are blocked, which is what defeats most injected script.
  • style-src 'self': no inline style="" attributes. Put styles in CSS files.
  • frame-ancestors 'none': no other site may put your pages in a frame. This replaces X-Frame-Options in modern browsers; send both for older ones.
  • object-src 'none' and base-uri 'self': close two old injection tricks.

The inline script problem

Most sites have one inline script they can't move: setting the dark/light theme before the first paint, so the page doesn't flash. There are two ways to allow it.

A nonce: a random value per response, added to both the header and the tag. It works, but every response must be generated fresh. A page served from an output cache carries an old nonce and the script is blocked.

A hash: the SHA-256 of the script's exact text. It never changes while the script doesn't, so cached pages stay valid. Compute it from the same constant you render:

csharp
public static class ThemeScript
{
    public const string Source =
        "(function(){var t=localStorage.getItem('theme')||(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light');document.documentElement.dataset.theme=t})();";

    public static readonly string CspHash =
        "'sha256-" + Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Source))) + "'";
}
html
<script>@Html.Raw(ThemeScript.Source)</script>
csharp
"script-src 'self' " + ThemeScript.CspHash,

The hash covers the exact characters between the tags. Rendering the script with extra whitespace, or editing it without recomputing, blocks it. Building both from one constant avoids that.

Move everything else out of the page

A strict CSP pushes you towards cleaner front-end code, which is a benefit in itself:

  • Inline handlers become listeners in a JS file: button.addEventListener("click", …).
  • Inline config becomes data-* attributes: <form data-save-url="/admin/posts/save">.
  • Inline styles become classes. Setting element.style.width from JavaScript is still allowed; only style="" in the markup is blocked.
  • JSON-LD (<script type="application/ld+json">) is data, not executed script, so CSP doesn't block it.

Roll it out without breaking pages

Start in report-only mode. The browser logs every violation to the console but blocks nothing:

csharp
h["Content-Security-Policy-Report-Only"] = Csp;

Click through every page, both themes, signed in and out, and fix each violation. When the console is quiet, switch to the enforcing header.

Common surprises:

  • Analytics or chat widgets need their domains in script-src and connect-src. Every one you add widens the policy, so add them deliberately.
  • Fonts from a CDN need font-src and style-src entries. Self-hosting removes the need.
  • Browser extensions inject scripts and show up as violations in report-only mode. Those aren't yours to fix.

HSTS, carefully

UseHsts() tells browsers to use HTTPS for your domain for a year. Once a browser has seen it, plain HTTP stops working for that domain. Make sure HTTPS works on every subdomain you serve before adding includeSubDomains, and leave HSTS off in development, where localhost certificates come and go.

Check the result

Open your site, then the browser's network tab, and look at the response headers of the HTML page. Online scanners such as securityheaders.com grade the result. Aim for every header in the table above, and a CSP without 'unsafe-inline'.

Wrapping up

Six headers, one middleware, and a CSP that allows your own files plus one hashed script. Roll the policy out in report-only mode first, move inline code into files as you find it, and you remove whole categories of attack without changing how the site looks.

Keep reading

All articles →
Security

JWT Authentication in ASP.NET Core: The Production Guide

Short-lived access tokens, rotating refresh tokens, role-based policies — and the defaults that quietly break your API.

6 min read
ASP.NET Core & Web APIs

Rate Limiting in ASP.NET Core: Protect Your API Without a Gateway

Fixed window, sliding window, token bucket and concurrency limiters with the built-in middleware, partitioned per client, with friendly 429s.

3 min read
Architecture & Production .NET

Background Jobs in ASP.NET Core with BackgroundService and PeriodicTimer

Run scheduled work inside your ASP.NET Core app: BackgroundService, PeriodicTimer, scoped DbContext, safe reruns, and when to reach for Hangfire.

4 min read