React inline styles blocked by CSP policy for 'style-src'
See original GitHub issueI’m working on an application that has a strict CSP policy including style-src, which prevents the possibility of using inline styles. If I attempt to use React’s builtin CSS templater with the following component, the styling is blocked with an error.
class SomeComponent extends React.Component {
constructor() {
super();
this.styles = {
backgroundColor: 'red',
color: 'blue',
};
}
render() {
return <div ref="someDiv" style={this.styles}>Some Component</div>;
}
}
DOM.render(<SomeComponent />, document.getElementById('main'));
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
I can get around this by manually manipulating the DOM’s style object after every React render:
class SomeComponent extends React.Component {
constructor() {
super();
this.styles = {
backgroundColor: 'red',
color: 'blue',
};
}
componentDidMount() {
_.extend(this.refs.someDiv.style, this.styles);
}
componentDidUpdate() {
_.extend(this.refs.someDiv.style, this.styles);
}
render() {
return <div ref="someDiv">Some Component</div>;
}
}
DOM.render(<SomeComponent />, document.getElementById('main'));
I’m wondering if React’s DOM engine can set the style object instead of serializing to a string and inserting a style attribute in the markup? This would make React adhere more tightly to CSP.
Would a pull request on this be welcomed?
Issue Analytics
- State:
- Created 8 years ago
- Comments:12 (1 by maintainers)
@sophiebits
Unfortunately that would make our React-powered sites vulnerable to clever attacks/injections, such as this CSS-only keylogger: https://no-csp-css-keylogger.badsite.io/
Do you believe that @xkr47’s proposed solution above a good one, as it seems to be? Thanks.
Yes! Scanning the server-side rendered html and adding sha256 for all
<script>
,<style>
and ‘style="…"things worked perfectly! No need for
’unsafe-inline’or
’nonce’` stuff. I will try to publish a npm module with my code. Will post about it here.