I am adding content-security-policy settings for my web app and would like to be strict about inline scripts and inline styles. I have inline scripts working properly but am having trouble with inline styles. For background, my web app uses Elixir/Phoenix on the back end and includes React components on the front end.
Nonce for Inline Scripts - Works
I have just a smattering of inline scripts to get the React components bootstrapped. Per CSP guidelines, I'm using nonce values to handle these inline scripts. Specifically, I generate a new nonce value server side on each page load and include it in the content-security-policy header and also inject it into a nonce attribute in the script tags using server side rendering. This works fine.
Nonce for Inline Styles - Doesn't Work
Inlines styles are another story. Inlines styles are pretty common in React. My hope was that I could use a similar nonce approach for this, but so far I have not been able to get it to work. Nonce values are listed in the style-src page at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src so it seems like this should work, though that section of the doc references scripts so maybe not. I have tried injecting a nonce attribute into the generated HTML, but this does not work. I continue to receive the normal error messages.
Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self' 'nonce-my-long-ugly-random-nonce-value'". Either the 'unsafe-inline' keyword, a hash ('sha256-specific-hash'), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.
I've been searching for a while and have yet to find any hint that nonce values work for inline styles, other than what I mention above. Can anyone confirm that nonce values work for inline styles?
If they don't work, it seems like using hashes is my next best bet. I can get hashes to work, by looking at each error message like the one above and adding the hash to the content-security-policy header. That is not a very scalable solution though, and if I have to go that route I'd like to know if anyone has come up with a way to automate generating the hashes without having to manually navigate everywhere in the app and look at the error message to get the hash.
Any help you can provide is appreciated.
Thanks. Justin
After looking at Content Security Policy allow inline style without unsafe-inline it appears this isn't supported, perhaps because the spec seems to imply that it is referring only to inline styles in a <style> tag, similar how the spec refers to inline scripts in a <script> tag.
Assuming that is correct, it looks like I'll have to go the hash route or add 'unsafe-inline' just for style-src.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With