I want to publish a web application with a strict Content Security Policy. The last remaining issue is: style-src 'self';
I get an error in the browser console saying that a resource was blocked from loading based on the style-src directive in the CSP. The error references code in the main..js file that is produced from ng build --prod
.
If I add 'unsafe-inline'
to the style-src
directive in the CSP, everything works fine, however, I do not want to do this.
Is there anything I can do in my code or build option to make the web application work with the more restrictive CSP?
I was using Angular 11 and just upgraded to 12 and have the same error.
Thanks!
Options for resolution:
1. Use SHA-256 hashes
If there is a relatively small amount of such violations, you can add their hashes. Example, if you see this in your log:
Add
'sha256-YpcdPia2p132TdnpnY8zwrWWSqByEKGZBY5iqsLBkSg='
You may also need'unsafe-hashes'
- depending on the context. Note: This approach is not easy to sustain. A small change in a style will force you to recreate the hash. It's useful only when you have a handful of such inline scripts.2. Nonces
You can use nonces to "bless" inline styles and approve them. However, even Google experts who advocate for CSP nonces don't usually deploy them on
style-src
- only onscript-src
. Note: This approach is hard to deploy. A unique nonce needs to be generated for every pageload.3. Use
'unsafe-inline'
- it's fine forstyle-src
(not great forscript-src
)Really, even setting a CSP with
style-src 'unsafe-inline' 'self' someurl.com;
is much safer than 99.9% of sites. More than accounts.google.com that does not restrictstyle-src
at all. Github have a fantastic high quality CSP withstyle-src: 'unsafe-inline'
Good luck!