Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

javascript - how to set socket.io origins to restrict connections to one url

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...