简体   繁体   English

nodeJS https-无法设置内容安全策略

[英]nodeJS https - unable to set Content-Security-Policy

I am trying to write a simple NodeJS HTTPS web server using HTTPS and Express that has a configurable Content-Security-Policy. 我正在尝试使用HTTPS和Express编写一个简单的NodeJS HTTPS Web服务器,该服务器具有可配置的Content-Security-Policy。

I try to set the Content-Security-Policy header attribute in the server response object, but always just sends "default-src 'self'". 我尝试在服务器响应对象中设置Content-Security-Policy标头属性,但始终只发送“ default-src'self'”。 it appears that the HTTPS module overwrites whatever I specify. 看来HTTPS模块会覆盖我指定的内容。

I have also tried using the helmet-csp npm package with no success either. 我也尝试过使用helmet-csp npm软件包,也没有成功。

Here's my code snippet: 这是我的代码段:

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

You just need to set it in the HTTP Header, not the HTML. 您只需要在HTTP标头(而不是HTML)中进行设置即可。 This is a working example with express 4 with a static server: 这是带有静态服务器的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); 

If you want more information about CSP, this is an excelent article: http://www.html5rocks.com/en/tutorials/security/content-security-policy/ 如果您想了解有关CSP的更多信息,这是一篇很棒的文章: http ://www.html5rocks.com/en/tutorials/security/content-security-policy/

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM