简体   繁体   中英

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.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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