nodeJS - where exactly can I put the Content Security Policy

十年热恋 提交于 2020-02-27 22:07:24

问题


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

回答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!




回答2:


For a node.js application without using any external framework e.g. express:

const http = require('http');

http.createServer((request, response) => {

    request.on('error', (err) => {
        console.error(err);

    // for this simple example I am not including the data event
    // e.g. if the request contains data in the body

    }).on('end', () => {

       response.on('error', (err) => {
           console.error(err);
       });

      // you can set your headers with setHeader or 
      // use writeHead as a "shortcut" to include the statusCode. 
      // Note writeHead won't cache results internally
      // and if used in conjuction with setHeader will take some sort of "precedence"

      response.writeHead(200, {
          "Content-Security-Policy": "default-src 'self'"

           // other security headers here...
      });

      response.end("<html><body><h1>Hello, Security Headers!</h1></body></html>");

  });
}).listen(8080);

See the node.js documentation for more details on setting headers on the response object



来源:https://stackoverflow.com/questions/21048252/nodejs-where-exactly-can-i-put-the-content-security-policy

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