How can I substitute the CSP nonce value in Angular's index.html using .net 7 (c#)?

Discussão em 'Angular' iniciado por Aceofspades25, Novembro 26, 2025.

  1. Using Angular 16, we can specify a CSP_NONCE injection token to be used in all inline styles and scripts (as described here). In this example, it gets the nonce from globalThis.myRandomNonceValue but I have no idea how that would be provided from the server.

    In another example I've seen, a meta tag is added to index.html that provides the nonce value for Angular to reference. Somehow before the page is served it is able to rewrite the index.html to add the nonce to the meta tag.

    Assuming my server side code is written in c# and runs on .net 7, this is what my code would look like in my Program.cs to generate a cryptographic-nonce and add it to a CSP header

    app.Use(async (context, next) =>
    {
    // cryptographic-noncing only supported in Angular 16
    var rng = RandomNumberGenerator.Create();
    var nonceBytes = new byte[32];
    rng.GetBytes(nonceBytes);
    var nonce = Convert.ToBase64String(nonceBytes);
    context.Response.Headers.Add("Content-Security-Policy", $"default-src 'self' 'nonce-{nonce}'");
    await next();
    });


    Given that my app is running in .net core

    What is the easiest / best way to also make the nonce available for Angular to reference?

    I could have swore I saw an example of how to get Angular to pick up the nonce value from the CSP HTTP Header but I cannot find it again

    Continue reading...

Compartilhe esta Página