0

I am implementing Content-Security-Policy header in my ASP.NET MVC project and my JS scripts doesn't work.

I added this tag

<add name="Content-Security-Policy" value="default-src 'self'; script-src 'self' https://code.jquery.com" />

and as you can see I added the source of my CDN for my script file.

If I add unsafe-inline at the end it works but I believe that's not the point.

Any help would be appreciated!

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • "*If I add `'unsafe-inline'` at the end it works but I believe that's not the point.*" Have a look into browser console and ensure that that's is the point. You have inline scripts at the page. – granty Jul 19 '21 at 14:34

1 Answers1

0

If I add unsafe-inline at the end it works but I believe that's not the point.

As you can see you have some kinds of inline scripts on the page. Main question is - is it:

  1. blocks of <script>...</script>
  2. or inline event handlers (eg <tag onload='...')
  3. or javascript:-navigation (eg <a href='void(0)').

Because (2) and (3) requires mandatory 'unsafe-inline' (or code refactoring).
The first one can be allowed through 'hash-value' or 'nonce-value'.

Google Chrome browser in the console error messages differs all these 3 types of inline script:

  1. Refused to execute inline script ...
  2. Refused to execute inline event handler ...
  3. Refused to run the JavaScript URL ...

In case of (2) you have to replace by some way all <tag onclick='...'> with addEventListener().

In case of (3) you have to replace <a href='void(0)'> with <a href='#'> or any other way remove javascript navitagtion from tags.

In case of (1) you have opts:

  • to add 'sha256-...' from the violation message in the Chrome console into script-src directive (if there is not a lot of those).

  • to use 'nonce-value'. Easiest way is to configure CSP using NWebsec.
    Websec package includes HtmlHelpers to add script and style 'nonces'.

An example for in ASP 4:

@using NWebsec.Mvc.HttpHeaders.Csp
<script @Html.CspScriptNonce()>var inline = 5;</script>

An example for ASP Core:

<script nws-csp-add-nonce="true">var inline = 5;</script>

Alternatively you can override HtmlTextWriter method to add nonces into script/style tags.

Since you do not provide any specific info regarding you case, it can be a lot of "If-Then-Else". Anyway so wide open question can not be exactly answered.

granty
  • 7,234
  • 1
  • 14
  • 21