Stefan Benz
Stefan Benz

Reputation: 39

Why does my code violate the Content Security Policy?

I want to defer non-critical css using the following mechanism:

<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">

I have the following Content Security Policy:

Content-Security-Policy: default-src 'self'; object-src 'none'; font-src 'self'; base-uri 'self'; connect-src 'self'; manifest-src 'self'; img-src 'self'; script-src 'self' 'nonce-7cc36362-697e-4b28-bdd9-0400d8923894' 'sha256-1jAmyYXcRq6zFldLe/GCgIDJBiOONdXjTLgEFMDnDSM='; style-src 'self'; form-action 'self'; frame-ancestors 'none'; media-src 'self'; report-uri /api/cspviolation

When trying to load and interpret the document, the browser blocks the execution of the onload event handler script because it violates the CSP, which I do not understand because the sha256 of that script is set in the script-src directive.

Any ideas? I've used an online sha256 generator generating the the sha256 set in the CSP. Sadly Chrome does not provide me the sha256 it wants in the console, which I've seen before.

Upvotes: 3

Views: 1971

Answers (2)

Halvor Sakshaug
Halvor Sakshaug

Reputation: 3455

Inline event handlers can only be whitelisted with a hash using 'unsafe-hashes' in CSP level 3, but this is not yet well supported in browsers. Check https://www.w3.org/TR/CSP3/#unsafe-hashes-usage for specification and the table in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy for browser compatibility.

You best option is probably to move the script to a separate file and adding an event listener.

Upvotes: 4

Stephen R
Stephen R

Reputation: 3897

You're using an inline script ("onload=..."), so either your CSP script-src needs to allow unsafe-inline, or you need to load the script differently.

Upvotes: -1

Related Questions