1

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 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the idea, but the key for me is that this has to work with the Node HTTPS module. As you can see in my code snippet, I am using Express in conjunction with HTTPS. And as you can see, my code is setting the CSP in the header, and not in the HTML

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.