'Adding nonce value to @Scripts.Render ASP.Net MVC razor pages with NWebSec

I am trying to implement Content-Security-Policy with the NWebSec NuGet package

The basic configuration level is working at this moment but trying to add nonce for each script and style in the project.

How to add a nonce to the below tags for inline?

@Styles.Render("~/Content/css/file")

For BundleConfig,

bundles.Add(new ScriptBundle("~/Content/Scripts").Include(
                "~/Content/Scripts/General.js"
                ));

I tried with a new class and it's working but with the NWebSec package I going nowhere. Below is their solution with @Html.CspScriptNonce() directives and this is working.

 <script @Html.CspScriptNonce()>document.write("Hello world")</script>
<style @Html.CspStyleNonce()>
   h1 {
          font-size: 10em;
        }
</style>


Solution 1:[1]

When using NWebSec with ASP.Net MCV Bundles, you can not apply a Nonce, but luckily you don't need to.

There might be something you need to change in your web.config though. In the nwebsec > httpHeaderSecurityModule > securityHttpHeaders > content-Security-Policy section, make sure that self="true" for both style-src and script-src. self="true" is the default, though, so if you don't need those elements for any other declarations, you can omit them.

Here's the nwebsec section in my web.config. I'm using both style and script bundles, and have no third-party scripts.

  <nwebsec>
    <httpHeaderSecurityModule xmlns="http://nwebsec.com/HttpHeaderSecurityModuleConfig.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="NWebsecConfig/HttpHeaderSecurityModuleConfig.xsd">
      <securityHttpHeaders>
        <content-Security-Policy enabled="true">
          <default-src self="true" />
          <font-src self="true">
            <add source="https://fonts.gstatic.com" />
          </font-src>
          <object-src none="true" />
          <style-src self="true">
            <add source="https://fonts.googleapis.com" />
          </style-src>
          <base-uri none="true" />
        </content-Security-Policy>
      </securityHttpHeaders>
    </httpHeaderSecurityModule>
  </nwebsec>

Solution 2:[2]

The solution I tried was to use @Styles.RenderFormat in the following way:

@Styles.RenderFormat("<link href=\"{0}\" rel=\"stylesheet\" " + @Html.CspStyleNonce() +"/>","~/Content/css/file")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steve Kerrick
Solution 2 Jeremy Caney