1

我正在尝试使用具有可配置 Content-Security-Policy 的 HTTPS 和 Express 编写一个简单的 NodeJS HTTPS Web 服务器。

我尝试在服务器响应对象中设置 Content-Security-Policy 标头属性,但始终只发送“default-src 'self'”。似乎 HTTPS 模块覆盖了我指定的任何内容。

我也尝试过使用helmet-csp npm 包,但也没有成功。

这是我的代码片段:

var app = express();
var sslOptions = {
    cert: fs.readFileSync(ourPath + "/certs/server.crt"),
    key: fs.readFileSync(ourPath + "/certs/server.pem")
};
var httpsServer = https.createServer(sslOptions, app);

var server = httpsServer.listen(secPort /*443*/, function () {
    console.log('HTTPS Server listening at port %d', secPort);
});

// Trap the incoming request, and preset the CSP in the response header
server.on('request',(req,res)=>{
    res.setHeader("Content-Security-policy","* 'inline-eval';");
});
4

1 回答 1

4

您只需在 HTTP 标头中设置它,而不是在 HTML 中。这是带有静态服务器的 express 4 的工作示例:

var express = require('express');
var app = express();


app.use(function(req, res, next) {
    res.setHeader("Content-Security-Policy", "script-src 'self' https://apis.google.com");
    return next();
});

app.use(express.static(__dirname + '/'));

app.listen(process.env.PORT || 3000);

如果您想了解有关 CSP 的更多信息,这是一篇出色的文章:http ://www.html5rocks.com/en/tutorials/security/content-security-policy/

希望有帮助!

于 2018-09-12T09:42:57.717 回答