0

我已经厌倦了下面的代码不起作用:

var WebSocketServer = require('ws').Server;
var wsServer = new WebSocketServer({port: 8080});

wsServer.on('connection', function(ws) {   
    if (ws.origin != 'http://example.com') {
        console.log('Origin was not http://example.com');
        return;
    }
});

此代码适用于 worlize 的 websocket 服务器包。但我更喜欢 einaros 的更好。但是,当我调查 ws.property 时,它包含如下内容:

headers: {
    ...
    origin: 'http://example.com'
    ...
},

那么如何验证浏览器请求的来源。

谢谢,

4

2 回答 2

2

从源代码中搜索我发现了一个我可以接受的解决方案。通过 verifyClient 选项

var webSockOpts=
    {port         :myport
    ,verifyClient : function (info, callback) {
        var question=url.parse(info.req.url, true, true);
        if (parseInt (question.query.API_KEY) === 123456789) {
           status= true; // I'm happy
           code  = 400;  // everything OK
           msg   = '';   // nothing to add
        } else {
           status= false; // I'm noy happy
           code  = 404;  //  key is invalid
           msg   = 'Demo requires API_KEY=123456789';
        }
        callback (status,code,msg);
      }
}
wsServer=new webSocket (webSockOpts);

在您的 HTML/JavaScript 中添加如下内容:

ws = new WebSocket('ws://' + host + ':4081' + '/log?API_KEY=123456789');
于 2014-10-20T11:16:42.463 回答
1

我最终可以找到它:

var domain = ws.upgradeReq.headers.origin;
于 2013-07-22T03:37:22.943 回答