如何将__webpack_nonce___的值与我的内容安全策略集成?

问题描述 投票:6回答:1

根据我对Content Security Policy的理解,nonce必须根据每个请求进行更改。这意味着(我认为)它必须在运行时在客户端生成,而不是在Webpack配置的构建时生成。我在我的应用程序中测试了the webpack_nonce functionality,效果很好。

不幸的是,我不确定如何将在客户端上运行时生成的值转换为实际的CSP策略,该策略可以设置为index.html文件(或某些等效文件)中的元标记,也可以设置为服务器本身。

我想你可以在客户端上动态设置CSP元标记,但这似乎是一种安全风险。我已经尝试了csp-webpack-plugin,它在构建时计算文件的哈希值,然后将它们添加到index.html。这个过程对我来说很有意义,它只是不支持我们的用例。

我只是觉得我错过了使用webpack_nonce的东西。

security webpack webpack-2 html-webpack-plugin
1个回答
3
投票

通过让webpack构建我们的索引页面(例如通过HtmlWebpackPlugin)作为模板然后动态地提供它,我们能够获得动态的nonce。这样,您可以将__webpack_nonce__设置为<%=nonce%>之类的插值表达式,并且服务器视图引擎可以在页面加载时在动态nonce中进行子操作。例如,如果您使用快递:

Webpack配置:

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: 'index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: __dirname + '/dist/index.ejs',
    })
  ]
}

Webpack入口点(index.js):

__webpack_nonce__ = '<%=nonce%>';

快递应用:

// Generate dynamic nonce on each request cycle
const uuid = require('node-uuid');
app.use((req, res, next) => {
  res.locals.nonce = uuid.v4();
  next();
});

app.set('view engine', 'ejs');
app.route('/').get((req, res, next) => {
  res.render('path/to/index.ejs', { nonce: res.locals.nonce });
});

注入的<script>标签将附加文字属性nonce=<%=nonce%>,然后服务器将在提供页面时进行插值。

请注意,如果您使用带有HtmlWebpackPlugin的自定义模板,您可能需要为ejs设置不同的插值分隔符,否则Webpack将在构建时而不是运行时插入nonce表达式。

快递应用:

const ejs = require('ejs);
ejs.delimiter = '?'; // Means instead use __webpack_nonce__ = '<?=nonce?>'
© www.soinside.com 2019 - 2024. All rights reserved.