Web application security is an important part of modern application development. ASP.NET Core provides several built-in protections, but applications must also defend against attacks that target browser-side code. Cross-Site Scripting (XSS) is one of the common risks when an application renders dynamic content or handles user-controlled input.
Content Security Policy (CSP) provides an additional layer of browser security. It allows developers to define which sources are trusted to load scripts, styles, images, fonts, and other resources. However, a strict CSP can block inline JavaScript and CSS that an application legitimately needs.
This is where CSP nonces become useful. A nonce is a unique, unpredictable value generated for an individual HTTP response. The application includes the value in its CSP header and adds the same value to approved script or style elements. The browser allows those elements to execute or apply while blocking inline content without a valid nonce.
In this article, we will explore how CSP nonces work, how to implement them in ASP.NET Core middleware, how to use them in Razor views, and how to avoid common security and caching mistakes.
Understanding Content Security Policy
Content Security Policy is a browser security mechanism that controls which resources a web page can load and execute.
A website can return a Content-Security-Policy HTTP response header containing rules for scripts, styles, images, fonts, connections, and other resource types.
For example:
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self';
This policy tells the browser to load resources from the application's own origin by default. It also restricts scripts and styles to the same origin.
If a page contains an inline script, the browser blocks it because the script is not explicitly authorized by the policy.
Consider the following HTML:
<script>
alert("Hello from ASP.NET Core");
</script>
When the response uses a strict script-src 'self' directive, the browser blocks this inline script.
This behavior is intentional. If an attacker manages to inject a script into the page, the browser should not automatically execute it.
However, many applications use inline scripts for initialization, dynamic configuration, and third-party component integration. A nonce allows the application to authorize specific inline scripts without allowing every inline script on the page.
What Is a CSP Nonce?
Nonce stands for number used once. In Content Security Policy, it is a cryptographically random value that authorizes specific script or style elements.
The application generates a new nonce for every HTML response. It then places the nonce in two locations:
The Content-Security-Policy response header.
The nonce attribute of each trusted script or style element.
For example, the response header might contain:
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-AbCdEf1234567890';
The corresponding HTML can contain:
<script nonce="AbCdEf1234567890">
console.log("This script is authorized");
</script>
The browser compares the nonce in the script element with the nonce in the CSP policy. If they match, the browser allows the script to execute.
An injected script without the correct nonce remains blocked.
A nonce does not identify whether the contents of a script are safe. It identifies whether the application has authorized that particular script element. Therefore, never add a nonce indiscriminately to untrusted content.
Why Use CSP Nonces in ASP.NET Core?
ASP.NET Core applications commonly generate HTML dynamically through Razor views, MVC controllers, and Razor Pages.
These applications may need inline scripts for page initialization or dynamic values. A strict CSP without nonces can block such scripts.
Using nonces provides several benefits:
Allows specific inline scripts without enabling all inline JavaScript.
Supports strict CSP policies.
Reduces the risk of injected scripts executing.
Works with dynamically generated HTML.
Allows different responses to use different authorization values.
Helps applications adopt stronger browser security policies without removing every inline script immediately.
For example, an ASP.NET Core application might render a dashboard with dynamic chart configuration. Instead of enabling unsafe-inline for every script, the application can authorize only the trusted initialization script.
Generating a Secure Nonce in ASP.NET Core
A nonce must be generated using a cryptographically secure random number generator.
.NET provides the RandomNumberGenerator class for this purpose. Avoid using Random, timestamps, GUID values, or predictable strings as security nonces.
A practical approach is to generate 16 random bytes and encode them using Base64.
Create a middleware class named CspNonceMiddleware.cs:
using System.Security.Cryptography;
public class CspNonceMiddleware
{
private readonly RequestDelegate _next;
public CspNonceMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var nonceBytes = RandomNumberGenerator.GetBytes(16);
var nonce = Convert.ToBase64String(nonceBytes);
context.Items["CspNonce"] = nonce;
await _next(context);
}
}
The middleware generates 128 bits of random data for every request.
The RandomNumberGenerator.GetBytes method provides cryptographically secure random bytes. The Base64 representation makes the value suitable for use in the CSP header and HTML nonce attribute.
The middleware stores the generated value in HttpContext.Items. This collection is useful for sharing request-specific information between middleware, controllers, and Razor views.
The same value must be used throughout the response. Generating a second nonce in a Razor view would cause a mismatch with the CSP header.
Creating a CSP Header Middleware
Generating a nonce is only one part of the implementation. The application must also include the value in the Content-Security-Policy response header.
Create another middleware class named CspHeaderMiddleware.cs:
public class CspHeaderMiddleware
{
private readonly RequestDelegate _next;
public CspHeaderMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var nonce = context.Items["CspNonce"]?.ToString();
if (!string.IsNullOrEmpty(nonce))
{
var policy =
$"default-src 'self'; " +
$"script-src 'self' 'nonce-{nonce}'; " +
$"style-src 'self' 'nonce-{nonce}'; " +
$"img-src 'self' data:; " +
$"font-src 'self'; " +
$"connect-src 'self'; " +
$"object-src 'none'; " +
$"base-uri 'self'; " +
$"frame-ancestors 'self'";
context.Response.Headers.ContentSecurityPolicy = policy;
}
await _next(context);
}
}
The middleware reads the nonce generated earlier and adds it to the CSP policy.
The policy contains several directives:
Directive | Purpose |
|---|
default-src | Defines the default resource loading policy |
script-src | Controls JavaScript execution |
style-src | Controls stylesheet loading and inline styles |
img-src | Controls image sources |
font-src | Controls font loading |
connect-src | Controls connections such as fetch and WebSocket |
object-src | Restricts plugin-based content |
base-uri | Controls the document base URL |
frame-ancestors | Controls which sites can embed the page |
The example is a starting policy, not a universal configuration. Applications using external APIs, CDNs, analytics, fonts, or embedded content must add the required trusted origins to the appropriate directives.
Avoid adding unsafe-inline to script-src simply to make blocked scripts work. Doing so can weaken the protection that the nonce is intended to provide.
Registering the Middleware in Program.cs
Middleware execution order is important.
The nonce must be generated before the CSP header is constructed. Both middleware components must also execute before the response starts.
Register them in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseMiddleware<CspNonceMiddleware>();
app.UseMiddleware<CspHeaderMiddleware>();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.Run();
The nonce middleware executes first and stores the value in the current request context.
The CSP middleware then creates the response policy using that value.
Because middleware order determines request and response processing, place the security header middleware early enough to cover the responses you intend to protect. If other middleware can produce HTML responses, ensure that those responses also receive the required policy.
For applications using static files, remember that static-file middleware can short-circuit the pipeline. A CSP header intended for HTML documents does not necessarily need to be applied to every static asset response.
Using the Nonce in Razor Views
After generating the nonce and adding it to the CSP header, Razor views need access to the same value.
You can retrieve it from HttpContext.Items.
For example, in a Razor view:
@{
var nonce = Context.Items["CspNonce"]?.ToString();
}
<script nonce="@nonce">
document.addEventListener("DOMContentLoaded", function () {
console.log("Authorized inline script");
});
</script>
Razor automatically encodes attribute values when rendering them in the HTML attribute context.
The generated HTML contains the same nonce used by the response header.
You can also expose the value through a view model or a dedicated view component when that better fits your application architecture.
Avoid manually generating another nonce inside the view. The browser requires an exact match between the policy and the authorized element.
Using a Razor Tag Helper for Nonces
If an application contains many inline script and style elements, manually retrieving the nonce in every view can become repetitive.
A custom Tag Helper provides a reusable solution.
Create a file named CspNonceTagHelper.cs:
using Microsoft.AspNetCore.Razor.TagHelpers;
[HtmlTargetElement("script", Attributes = "asp-csp-nonce")]
[HtmlTargetElement("style", Attributes = "asp-csp-nonce")]
public class CspNonceTagHelper : TagHelper
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CspNonceTagHelper(
IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public override void Process(
TagHelperContext context,
TagHelperOutput output)
{
var httpContext = _httpContextAccessor.HttpContext;
var nonce = httpContext?.Items["CspNonce"]?.ToString();
if (!string.IsNullOrEmpty(nonce))
{
output.Attributes.SetAttribute("nonce", nonce);
}
output.Attributes.RemoveAll("asp-csp-nonce");
}
}
Register the HTTP context accessor in Program.cs:
builder.Services.AddHttpContextAccessor();
Then register the Tag Helper in Views/_ViewImports.cshtml:
@addTagHelper *, YourApplication
Replace YourApplication with the assembly name containing the Tag Helper.
Now you can use the custom attribute in Razor views:
<script asp-csp-nonce>
console.log("Script authorized by CSP");
</script>
<style asp-csp-nonce>
.dashboard-title {
color: darkblue;
}
</style>
The Tag Helper reads the request nonce and adds the standard nonce attribute during Razor rendering.
This approach makes it easier to apply nonce authorization consistently across multiple views.
For production applications, you can also consider established security-header libraries that provide nonce generation, CSP configuration, and Razor Tag Helpers. Review their current maintenance status and implementation details before selecting one.
Adding Nonces to External Script Files
CSP nonces are not limited to inline scripts. They can also authorize external script elements.
For example:
<script
src="~/js/dashboard.js"
asp-csp-nonce
defer>
</script>
The rendered script element receives the nonce attribute through the Tag Helper.
However, a nonce does not replace all other resource restrictions. The CSP policy must still allow the script's source through the appropriate directive.
For example, if the script is served from the application's own origin, script-src 'self' permits that source. The nonce provides an additional authorization mechanism for the individual script element.
This is useful when an application wants a stricter script policy while supporting both local JavaScript files and selected inline initialization code.
Nonces Versus Hashes in CSP
CSP supports both nonces and hashes for authorizing inline scripts and styles.
A nonce is generated dynamically for each response. A hash is calculated from the exact contents of a script or style block.
For example, a hash-based policy might contain:
Content-Security-Policy: script-src 'self' 'sha256-BASE64_HASH_VALUE';
The browser calculates the hash of the inline script and compares it with the value in the policy.
The following table explains the differences:
Feature | Nonce | Hash |
|---|
Value generation | Random value per response | Calculated from content |
Suitable for dynamic scripts | Yes | Usually less convenient |
Suitable for static inline scripts | Yes | Yes |
Requires HTML modification | Add nonce attribute | No nonce attribute |
Changes when script content changes | No | Yes |
Works with external script elements | Yes, with source policy requirements | Browser support and integrity requirements vary |
Use nonces when the application generates dynamic HTML and needs to authorize selected script elements.
Use hashes when inline script content is stable and can be identified by its exact contents.
For static single-page applications, hash-based policies with Subresource Integrity may be more practical than generating response-specific nonces.
Important Security Considerations
Generate a new nonce for every response
Never reuse a nonce across page requests. A predictable or reused nonce weakens the security model.
Generate it using a cryptographically secure random number generator.
Never accept a nonce from the client
Do not read a nonce from query parameters, cookies, or arbitrary request headers and use it directly in the CSP policy.
The server must generate and control the nonce.
Keep the same nonce throughout one response
The CSP header and every authorized element in the HTML response must use the same value.
Do not generate separate values in middleware, controllers, and Razor views.
Avoid unsafe-inline
Do not add unsafe-inline to script-src simply because an inline script is blocked.
Use nonces or hashes to authorize the scripts that the application actually trusts.
Review third-party resources
External libraries, analytics tools, payment integrations, and content delivery networks may require additional CSP directives.
Allow only the origins that the application needs.
Be careful with caching
A nonce-bearing HTML response must not be cached and served to another user with the same nonce.
If a shared cache stores the HTML response, the CSP header and HTML can be replayed together. This defeats the expectation that a nonce is fresh for each response.
For personalized or nonce-bearing HTML, configure caching appropriately. If caching is necessary, design a safe strategy that ensures the policy and HTML remain correctly synchronized and that nonces are not reused across responses.
Keep output encoding enabled
A nonce does not replace HTML encoding, input validation, or other XSS prevention techniques.
Continue using Razor's default output encoding and avoid rendering untrusted input as raw HTML.
Testing CSP Nonces in the Browser
After implementing the middleware and Tag Helper, test the application in a browser.
Open the application and inspect the document response in the browser's developer tools.
Check the following:
Open the Network tab.
Select the HTML document request.
Inspect the response headers.
Locate the Content-Security-Policy header.
Open the rendered page source.
Verify that trusted script elements contain the corresponding nonce.
You can also test an inline script without a nonce.
For example:
<script>
console.log("This script should be blocked");
</script>
When the CSP policy does not authorize this script, the browser should block it and report a CSP violation in the console.
Then verify that the authorized script executes successfully.
Run these tests using multiple requests. The nonce should change between responses while remaining consistent between the header and the corresponding HTML elements within each response.
Common Problems and Troubleshooting
Problem | Possible cause | Solution |
|---|
Inline script is blocked | Missing nonce attribute | Add the generated nonce to the script element |
Script has a nonce but still fails | Header and HTML use different values | Generate the nonce once per request and share it |
Nonce is missing in Razor | Middleware did not execute | Check middleware registration and execution order |
External JavaScript is blocked | Script source is not allowed | Review script-src and the resource origin |
CSS is blocked | Style policy does not authorize the resource | Review style-src and nonce configuration |
CSP header is missing | Response started before the header was set | Set the header before writing the response |
Scripts work locally but fail in production | Production uses a stricter policy or different resources | Inspect browser console violations and deployed headers |
Different users receive the same nonce | Shared HTML caching is reusing responses | Review caching and ensure nonce-bearing HTML is not reused |
The browser console is particularly useful for diagnosing CSP failures. It identifies the resource or operation that the current policy blocks.
Best Practices for ASP.NET Core CSP Implementation
Generate nonces with RandomNumberGenerator.
Use at least 128 bits of cryptographically secure random data.
Generate one nonce per HTML response.
Store the nonce in request-specific context.
Use middleware to keep CSP header generation consistent.
Use Tag Helpers to avoid repeating nonce retrieval logic.
Start with a restrictive policy and add only required resource origins.
Avoid unsafe-inline and unsafe-eval wherever possible.
Configure caching carefully for dynamic HTML responses.
Test policies in report-only mode before enforcing a strict policy across an existing application.
Continue using HTML encoding and input validation to prevent XSS.
Advantages and Disadvantages
Advantages
Provides stronger control over inline JavaScript and CSS.
Helps prevent injected scripts from executing.
Supports dynamic Razor-generated HTML.
Works with external scripts when the source policy permits them.
Allows developers to adopt a stricter CSP without removing every inline script.
Can be implemented through reusable ASP.NET Core middleware and Tag Helpers.
Disadvantages
Requires additional middleware and view configuration.
Every authorized script or style element must receive the correct nonce.
Caching must be configured carefully.
Third-party libraries may require CSP policy changes.
A nonce does not protect against every XSS vulnerability.
Existing applications may require changes to inline scripts and event handlers.
Conclusion
Content Security Policy nonces provide a practical way to authorize trusted inline scripts and styles in ASP.NET Core applications without enabling unrestricted inline execution.
By generating a cryptographically secure nonce for each response, storing it in the request context, and using the same value in the CSP header and Razor elements, developers can implement a stronger browser security policy.
ASP.NET Core middleware provides a reusable place to generate the nonce and construct the response header. Razor Tag Helpers make it easier to apply the nonce consistently across views.
However, CSP should be treated as one layer of a broader security strategy. Continue using output encoding, input validation, secure configuration, and appropriate caching controls.
A carefully designed CSP policy, combined with per-response nonces, helps ASP.NET Core applications reduce the impact of script injection attacks while maintaining the flexibility required by modern web applications.
Join the conversation! Your thoughts help the community grow.