Firefox clears all inline style attributes when send header 'Content-Security-Policy'

693 Views Asked by At

Why does adding the following header cause Firefox only to empty all style="" attributes when rendered in the browser?

context.HttpContext.Response.Headers.Add("Content-Security-Policy", "style-src-attr 'unsafe-inline'; script-src-elem 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'self'");

Chrome and Edge browser show all content correct that means the style attribute`s value was not cleared to "".

2

There are 2 best solutions below

8
VDWWD On

First of all I could not reproduce the problem. When I added your Content-Security-Policy Firefox displayed inline styles just fine (v 70.0.1, 64 bit).

Then I tested your CSP with https://cspvalidator.org and it gave the following errors

1:1: Unrecognised directive-name: "style-src-attr".

1:33: Unrecognised directive-name: "script-src-elem".

Which would make sense since those attributes do not exist according the site https://content-security-policy.com/

So the CSP should propably be

"style-src 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'self'"
1
Vaibhav J On

The directives and syntax both you have used are valid but as per Content Security Policy Level 3 specifications, which are under Working Draft status right now.

Modern Chrome and Edge browsers are now fully support Content Security Policy Level 2 specifications as well as Content Security Policy Level 3 specifications partially. While Firefox has partial support to Content Security Policy Level 2 and Level 3 specifications till now, and this is the reason why Chrome and Edge browser showing all your content correct but Firefox. (please update your Firefox version and then re-check).

https://caniuse.com/#search=content%20security%20policy%20level

enter image description here

FYI, If your browser supports, style-src-attr can be used in conjunction with style-src. If this directive is absent, the user agent will look for the style-src directive, and if both of them are absent, fallback to default-src directive.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src-attr

Coming back to answer, now resolve this issue your Content Security policy header should be like below which is supported by almost all browsers.

context.HttpContext.Response.Headers.Add("Content-Security-Policy","style-src 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'self'");

Update:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src-attr#Browser_compatibility

enter image description here

This is a bug in Mozilla, which is already reported by someone ten months ago, maybe fixed in new updates.

https://bugzilla.mozilla.org/show_bug.cgi?id=1529338