如何设置 socket.io origins 以限制连接到一个 url [英] how to set socket.io origins to restrict connections to one url

查看:33
本文介绍了如何设置 socket.io origins 以限制连接到一个 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个 html 站点和一个为该网站提供服务的 node.js 服务器.网站和服务器使用 socke.io 交换数据.我们在文档中发现了这一点:

origins 默认为 *:*允许连接到 Socket.IO 服务器的来源.

我们的 html.site 位于 http://questionexample.com/page1 上.只有这个网站可以连接到我们的服务器.(但每个人都可以连接到那个网站.)我们必须如何设置原点?

解决方案

如果你深入研究 Socket.io 源代码,你会发现这样几行:

var origin = request.headers.origin ||request.headers.referer, origins = this.get('origins');...var 部分 = url.parse(origin);部件.端口 = 部件.端口 ||80;正常=~origins.indexOf(parts.hostname + ':' + parts.port) ||~origins.indexOf(parts.hostname + ':*') ||~origins.indexOf('*:' + parts.port);

如您所见,Socket.io 获取来自客户端的来源(或引用者),检索域名和端口,并与您指定的 origins 选项进行比较.

所以有效的 origins 值为(* 表示任何"):

  • testsite.com:80
  • http://testsite.com:80
  • http://*:8080
  • *:8080
  • testsite.com:* http://someotherdomain.com:8080 (多个来源以空格分隔)
  • testsite.com:*/somepath (socket.io 会忽略/somepath)
  • *:*

这些都是无效的(因为没有端口号):

  • testsite.com
  • http://testsite.com
  • http://testsite.com/somepath

另请注意,如果您指定 sub.testsite.com 作为来源值,testsite.com 将是 valid 来源.

We have one html site and one node.js server which serves that website. The website and the server exchange data using socke.io. We found this in the documentation:

origins defaults to *:* The origins that are allowed to connect to the Socket.IO server.

Our html.site is on http://questionexample.com/page1 . Only this site may connect to our server.(But everyone may connect to that website.) How do we have to set the origins?

解决方案

If you dig into Socket.io source code, you will find such lines:

var origin = request.headers.origin || request.headers.referer
  , origins = this.get('origins');

...

var parts = url.parse(origin);
parts.port = parts.port || 80;
var ok =
  ~origins.indexOf(parts.hostname + ':' + parts.port) ||
  ~origins.indexOf(parts.hostname + ':*') ||
  ~origins.indexOf('*:' + parts.port);

As you can see Socket.io takes origin (or referer) that came from the client, retrieves domain name and port, and compares with the origins option you specified.

So the valid origins values are (* means "any"):

  • testsite.com:80
  • http://testsite.com:80
  • http://*:8080
  • *:8080
  • testsite.com:* http://someotherdomain.com:8080 (multiple origins separated by space)
  • testsite.com:*/somepath (socket.io will ignore /somepath)
  • *:*

And these are invalid (because no port number):

  • testsite.com
  • http://testsite.com
  • http://testsite.com/somepath

Also note that if you specify sub.testsite.com as origins value, the testsite.com will be valid origin.

这篇关于如何设置 socket.io origins 以限制连接到一个 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆