Note: Disallowing inline styles and inline scripts is one of the biggest security wins CSP provides. However, if you absolutely have to use it, there are a few mechanisms that will allow them.
To allow inline styles, 'unsafe-inline'
, a nonce-source or a hash-source that matches the inline block can be specified.
Content-Security-Policy: style-src 'unsafe-inline';
The above Content Security Policy will allow inline styles like the <style>
element, and the style
attribute on any element:
<style>
#inline-style {
background: red;
}
</style>
<div style="display:none">Foo</div>
You can use a nonce-source to only allow specific inline style blocks:
You will have to set the same nonce on the <style>
element:
<style nonce="2726c7f26c">
#inline-style {
background: red;
}
</style>
Alternatively, you can create hashes from your inline styles. CSP supports sha256, sha384 and sha512. The binary form of the hash has to be encoded with base64. You can obtain the hash of a string on the command line via the openssl
program:
echo -n "#inline-style { background: red; }" | openssl dgst -sha256 -binary | openssl enc -base64
You can use a hash-source to only allow specific inline style blocks:
When generating the hash, don't include the <style>
tags and note that capitalization and whitespace matter, including leading or trailing whitespace.
<style>
#inline-style {
background: red;
}
</style>