nodeJS https - unable to set Content-Security-Policy

半腔热情 提交于 2019-12-11 17:55:55

问题


I am trying to write a simple NodeJS HTTPS web server using HTTPS and Express that has a configurable 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'". it appears that the HTTPS module overwrites whatever I specify.

I have also tried using the helmet-csp npm package with no success either.

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

回答1:


You just need to set it in the HTTP Header, not the HTML. This is a working example with express 4 with a static server:

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/

Hope that helps!



来源:https://stackoverflow.com/questions/52291783/nodejs-https-unable-to-set-content-security-policy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!