Course contentsShow
← C#
Lesson 1396 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Security Headers and CSP

Configure Content Security Policies to restrict executable scripts for hardened security.

In this lesson, you will learn how to harden your Blazor applications against cross-site scripting (XSS) and data injection attacks by implementing Content Security Policies (CSP).

The Concept of CSP

A Content Security Policy is a security layer that allows you to control which resources (such as scripts, images, and stylesheets) the browser is allowed to load. By default, browsers are quite permissive, which creates a window for malicious actors to inject unauthorized executable scripts. A CSP acts as an "allow-list" for your application's assets.

Implementing CSP in ASP.NET Core

In a Blazor or Razor application, you typically apply CSP headers using middleware. Since these headers are sent by the server, you can inject them into every HTTP response.

To restrict executable scripts to only your own origin—effectively blocking inline scripts and external malicious sources—you would define a policy header like this:

app.Use(async (context, next) =>
{
    // Restricts scripts to the origin, prevents 'unsafe-inline'
    context.Response.Headers.Add("Content-Security-Policy", 
        "default-src 'self'; script-src 'self'; object-src 'none';");
    await next();
});

Why This Matters for Blazor

Blazor Server and Wasm rely heavily on JavaScript interop (IJSRuntime). If your application is compromised, an attacker might attempt to inject a <script> tag that steals session tokens. By setting script-src 'self', you instruct the browser to ignore any script not served directly from your server.

Note that Blazor itself requires specific configurations. Because Blazor needs to execute its own bootstrapping scripts, a strict CSP might initially break your app. You may need to use nonce (number used once) or hash-based policies to allow Blazor's required startup scripts while still blocking unauthorized code.

When you define your policy, always use report-to or report-uri directives during development. This allows the browser to send violation reports to a logging endpoint, helping you identify what your policy is blocking before you enforce it strictly in production.

Key Takeaway: A Content Security Policy acts as a browser-enforced whitelist that neutralizes XSS attacks by restricting the origin and execution of scripts within your Blazor application.