Adding CSP Header- Allowing inline script using 'nonce' - DotNet example.

How to add nonce in Content Security Policy header dynamically to inline scripts in a C# .NET application.

To add a nonce to the Content Security Policy (CSP) header dynamically for inline scripts using C#, you need to follow these steps:

*The provided code snippets are for reference only. Developers should implement their own solutions based on their application's existing design.

1. Create a middleware to generate a unique nonce per request and apply it to the CSP header.

CSP Middleware (CspNonceMiddleware.cs)

using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
public class CspNonceMiddleware
{
    private readonly RequestDelegate _next;
    public CspNonceMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        // Generate a secure nonce
        var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(16));

        // Store nonce in HttpContext to use in views
        context.Items["CSPNonce"] = nonce;

        // Add CSP header with nonce
        context.Response.Headers.Add("Content-Security-Policy",
            $"default-src 'self'; script-src 'self' 'nonce-{nonce}' https://www.googletagmanager.com https://example.com/external.js;");

        await _next(context);
    }
}

Register Middleware in Program.cs

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseMiddleware<CspNonceMiddleware>();

app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();

Apply the Nonce to Inline Scripts in Razor Views

In Razor views (.cshtml), retrieve the nonce from HttpContext.Items and use it.

@{
    var nonce = Context.Items["CSPNonce"] as string;
}
<script nonce="@nonce">
    console.log("This inline script is now CSP compliant!");
</script>

Applying Nonce to Google Analytics (Separate <script> Tag)

<script nonce="@nonce">
    (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM-XXXXXX');
</script>

Applying Nonce to an External JavaScript File

If you are loading an external JavaScript file dynamically using an inline script, apply the nonce like this:

<script nonce="@nonce">
    var script = document.createElement("script");
    script.src = "https://example.com/external.js";
    script.nonce = "@nonce";
    document.head.appendChild(script);
</script>

 

Page 1 of this article:

https://community.veracode.com/s/article/How-to-fix-CWE-829-Add-CSP-header-correctly

Page 2 : Java J2EE example.

https://community.veracode.com/s/article/Adding-CSP-Header-Allowing-inline-script-using-nonce-java

 

Topics (0)

Related Topics

    Ask the Community

    Get answers, share a use case, discuss your favorite features, or get input from the Community.