If you are using webpack here is a instruction how to do it at least per build in SPA:
- add this into your html template(entry point, for ne it is index.html which is specified in WebPack):
<meta http-equiv="Content-Security-Policy" content="%%CSP_CONTENT%%">
- Install
csp-html-webpack-plugin
and go into your webpack:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CspHtmlWebpackPlugin = require('csp-html-webpack-plugin');
const generatedNonce = crypto.randomBytes(16).toString('base64');
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
'css-loader',
],
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.EMOTIONAL_NONCE': JSON.stringify(generatedNonce),
}),
new MiniCssExtractPlugin({
filename: 'css/[name].[hash].css',
chunkFilename: 'css/[id].[hash].css',
}),
new CspHtmlWebpackPlugin(
{
'base-uri': "'self'",
'default-src': [
"'self'"
],
'object-src': "'none'",
'script-src': "'self'",
'style-src': [
"'self'",
`'nonce-${generatedNonce}'`,
],
},
{
enabled: true,
hashEnabled: {
'style-src': false,
},
nonceEnabled: {
'style-src': false,
},
}
)
- Then as per this article from MUI(https://mui.com/material-ui/guides/content-security-policy/):
import createCache from '@emotion/cache';
const emotionalNonce = process.env.EMOTIONAL_NONCE;
const styleCache = createCache({
key: 'YourCacheKey',
nonce: emotionalNonce,
});
ReactDOM.render(
<CacheProvider value={styleCache}>
<Router>
<App />
</Router>
</CacheProvider>,
document.getElementById('root')
);
NOTE: for dynamic elements(aka modals MUI Modals), if you are rendering it via code don't forget to create another cache provider or reuse existing one and wrap the existing code, because it will be inserted NOT in root container of your React application by default.
<meta property="csp-nonce" content="123456" />
in the<head>
element as described on the Material-UI website under guides and csp, but the new<style>
element that are added at runtime in the browser do not include the nonce, but look like this:<style type="text/css" data-jss data-meta-"MuiInputLabel" nonce>
. The nonce attribute is there in the '<style>' tag but it has no value. Could anyone solve that? – Prorateindex.html
if you are only serving your site statically? – Mccorkle