Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeJS - where exactly can I put the Content Security Policy

Tags:

I don't know where to apply the Content Security Policy (CSP) snippet below in my code;

Content-Security-Policy: script-src 'self' https://apis.google.com

Should it be in the HTML?

Will it be best implemented in JavaScript as in the code snippet below?

var policy = "default-src 'self'";
http.createServer(function (req, res) {
    res.writeHead(200, {
        'Content-Security-Policy': policy
    });
});
like image 204
user2520410 Avatar asked Jan 10 '14 15:01

user2520410


People also ask

Where do you write Content-Security-Policy?

To enable CSP, you need to configure your web server to return the Content-Security-Policy HTTP header. (Sometimes you may see mentions of the X-Content-Security-Policy header, but that's an older version and you don't need to specify it anymore.)

Where do I put Content-Security-Policy in HTML?

To add this custom meta tag, you can go to www.yourStore.com/Admin/Setting/GeneralCommon and find Custom <head> tag and add this as shown in the image below. Content Security Policy protects against Cross Site Scripting (XSS) and other forms of attacks such as ClickJacking.


2 Answers

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!

like image 181
Juan Manuel Arias Avatar answered Oct 17 '22 03:10

Juan Manuel Arias


If you are using Express, I suggest taking a look at helmet. In addition to increased options & flexibility (handling CSP violations, nonces...etc), there are a lot of inconsistencies in how browsers implement CSP. Helmet looks at the user-agent of the browser and sets the appropriate header and value for that browser. If no user-agent is matched, it will set all the headers with the 2.0 spec.

// Make sure you run "npm install helmet-csp" to get the csp package.
const csp = require('helmet-csp')

app.use(csp({
  directives: {
    defaultSrc: ["'self'"],
    styleSrc: ["'self'", 'maxcdn.bootstrapcdn.com']
  }
}))
like image 24
Kevin Farrugia Avatar answered Oct 17 '22 02:10

Kevin Farrugia