Search code examples
javascriptjqueryangularcontent-security-policy

Why CSP header block jQuery on dev server, but work on localhost?


Hello we try to implement CSP header to our Angular application and I faced a problem with jQuery. CSP blocked jquery because it executes inline script, which is not allowed by my rules, 'unsafe-inline' in script-src not added. But on localhost everything works fine, on dev server not. Why its happend ? And how can I allow to work jquery scripts without 'unsafe-inline'. Script file loaded from same origin not from cdn. Error:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval' 'nonce-11111' https://*.website.com http://cdn.heapanalytics.com". Either the 'unsafe-inline' keyword, a hash ('sha256-wW7QqtXdIoLePBBqZfs1uttj5IW0GdlgNOmzyyPk7Xg='), or a nonce ('nonce-...') is required to enable inline execution.

Code with error:

function b(e, t, n) {
    var r, i, o = (n = n || E).createElement("script");
    if (o.text = e,
    t)
        for (r in c)
            (i = t[r] || t.getAttribute && t.getAttribute(r)) && o.setAttribute(r, i);
    n.head.appendChild(o).parentNode.removeChild(o) // this line
}

CSP rules:

<meta
  http-equiv="Content-Security-Policy"
  content="
  default-src 'self' https://*.website.com https://s3.amazonaws.com/bucket/ https://bucket.s3.amazonaws.com/;
  script-src 'self' 'unsafe-eval' 'nonce-11111' https://*.website.com http://cdn.heapanalytics.com;
  style-src 'self' 'unsafe-inline' https://*.website.com; 
  font-src 'self' https://*.website.com; 
  img-src 'self' https://*.website.com https://s3.amazonaws.com/bucket/ https://heapanalytics.com data:;"
/>

Nonce used for script in root html for analitics. I tried hash, but it's also not work.


Solution

  • It is because .createElement("script") tries to create script (unsafe inline) which doesn't have nonce neither hash. You might be looking for CSP - Strict dynamic which specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. (source: MDN)

    You also asked "Why its happend?"
    It's very hard to tell what and why a particular call is made without a code sample, but you could find out more information in this question: jQuery 3.1.1 violation of CSP directive