[英]nodeJS - where exactly can I put the Content Security Policy
我不知道在我的代碼中在哪里應用下面的內容安全策略 (CSP) 片段;
Content-Security-Policy: script-src 'self' https://apis.google.com
它應該在 HTML 中嗎?
它是否最好在 JavaScript 中實現,如下面的代碼片段所示?
var policy = "default-src 'self'";
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Security-Policy': policy
});
});
您只需要在 HTTP 標頭中設置它,而不是在 HTML 中。 這是帶有靜態服務器的 express 4 的工作示例:
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);
如果您想了解有關 CSP 的更多信息,這是一篇很棒的文章: http ://www.html5rocks.com/en/tutorials/security/content-security-policy/
希望有幫助!
對於不使用任何外部框架的node.js
應用程序,例如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);
有關在響應對象上設置標頭的更多詳細信息, 請參閱 node.js 文檔
如果您使用 Express,我建議您看一下頭盔。 除了增加的選項和靈活性(處理 CSP 違規、隨機數等)之外,瀏覽器如何實現 CSP 還存在很多不一致之處。 Helmet 查看瀏覽器的用戶代理並為該瀏覽器設置適當的標頭和值。 如果沒有匹配的用戶代理,它將使用 2.0 規范設置所有標頭。
// 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']
}
}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.