【发布时间】:2015-01-24 04:49:30
【问题描述】:
我正在尝试在节点服务器中实施内容安全策略 (CSP),但在设置 socket.io 时遇到了问题。看起来我在下面的代码中错误地设置了connectSrc。有人可以建议设置头盔的正确方法,以便浏览器允许网络套接字连接吗?提前致谢!
我正在使用头盔模块来生成 CSP;以下是设置 CSP 的代码:
securitySetup = function(app) {
var connectSources, helmet, scriptSources, styleSources;
helmet = require("helmet");
app.use(helmet());
app.use(helmet.hidePoweredBy());
app.use(helmet.noSniff());
app.use(helmet.crossdomain());
scriptSources = ["'self'", "'unsafe-inline'", "'unsafe-eval'", "ajax.googleapis.com"];
styleSources = ["'self'", "'unsafe-inline'", "ajax.googleapis.com"];
connectSources = ["'self'"];
return app.use(helmet.contentSecurityPolicy({
defaultSrc: ["'self'"],
scriptSrc: scriptSources,
styleSrc: styleSources,
connectSrc: connectSources,
reportUri: '/report-violation',
reportOnly: false,
setAllHeaders: false,
safari5: false
}));
};
这适用于所有 HTTP/AJAX 流量,但对于 ws:// 协议失败。建立 socket.io 连接时,我在 chrome 调试器中收到此错误:
Refused to connect to 'ws://localhost:3000/socket.io/1/websocket/ubexeZHZiAHwAV53WQ7u' because it violates the following Content Security Policy directive: "connect-src 'self'".
【问题讨论】:
-
我认为你的
connectSources规则是负责任的。为您的应用程序提供服务的网络服务器是否也在端口 3000 上运行? content-security-policy.com 在 Source List Reference 'self' 下说:允许从同一来源(相同的方案、主机和端口)加载资源。 -
@marco:是的,Web 套接字服务器与 Web 应用程序的 http 服务器是同一台服务器。看起来相同的“方案”部分是问题所在(ws:// vs http://)
-
那么我认为 Patrik Simeks 的回答也应该适合你。也许您可以对此发表评论或接受它作为正确答案(如果有效)?
标签: javascript node.js websocket socket.io content-security-policy