Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 432
Stefan Benz Avatar asked Jun 24 '26 03:06

Stefan Benz


1 Answers

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.

like image 83
Halvor Sakshaug Avatar answered Jun 25 '26 18:06

Halvor Sakshaug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!