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
nonce
attribute; see w3c.github.io/webappsec-csp/#is-element-nonceable. Also thenonce-source
source expression is valid in any serialized source list — w3c.github.io/webappsec-csp/#grammardef-source-expression — and thestyle-src
directive allows any serialized source list as its value w3c.github.io/webappsec-csp/#directive-style-src. So that all means that per the CSP spec, browsers are required to support the use of nonces for inline style elements (not just for scripts). – sideshowbarker