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>
2
Answers
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 thenwebsec > httpHeaderSecurityModule > securityHttpHeaders > content-Security-Policy
section, make sure thatself="true"
for bothstyle-src
andscript-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.The solution I tried was to use
@Styles.RenderFormat
in the following way: