【问题标题】:nodeJS https - unable to set Content-Security-PolicynodeJS https - 无法设置 Content-Security-Policy
【发布时间】:2019-02-16 21:28:21
【问题描述】:

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

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

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

这是我的代码 sn-p:

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';");
});

【问题讨论】:

    标签: node.js https content-security-policy helmet.js


    【解决方案1】:

    您只需在 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/

    希望有帮助!

    【讨论】:

    • 感谢您的想法,但对我来说关键是它必须与 Node HTTPS 模块一起使用。正如您在我的代码 sn-p 中看到的,我将 Express 与 HTTPS 结合使用。如您所见,我的代码是在标头中设置 CSP,而不是在 HTML 中
    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 2021-04-13
    • 2018-05-12
    • 2018-08-13
    • 2019-11-28
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多