使用回送令牌来validationsocket.io

我正在使用loopback 2.0和socket.io 1.0.6。

我想使用环回authentication方法来authenticationsocket.io。

我发现了在loopback / lib / middleware / token.js中validation用户的方法。 https://github.com/strongloop/loopback/blob/master/lib/middleware/token.js

然后我写如下:

var loopback = require('loopback'); var ioapp = module.exports = socketio; function socketio(server) { var io = require('socket.io')(server); // auth io.use(function(socket, next) { loopback.token()(socket.request, null, next); }); // listeners ... return io; }; 

但实际上我不会工作,并导致这样的错误。

 /Users/.../project_root/node_modules/loopback/lib/models/access-token.js:201 id = req.param(params[i]); ^ TypeError: Object #<IncomingMessage> has no method 'param' at tokenIdForRequest (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/loopback/lib/models/access-token.js:201:14) at Function.AccessToken.findForRequest (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/loopback/lib/models/access-token.js:123:12) at /Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/loopback/lib/middleware/token.js:53:16 at Array.0 (/Users/ksuzuki/Projects/appsocially/repo/chat-center/server/socket.js:15:28) at run (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/namespace.js:114:11) at Namespace.run (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/namespace.js:126:3) at Namespace.add (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/namespace.js:155:8) at Client.connect (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/client.js:67:20) at Server.onconnection (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/index.js:309:10) at Server.EventEmitter.emit (events.js:95:17) 

我猜这是因为我把错误的对象types传递给loopback.token()方法。

       

网上收集的解决方案 "使用回送令牌来validationsocket.io"

那么我相信Loopback标记是build立用于明确的请求对象。 在最新版本(2.x)中,如果您覆盖AccessToken.findForRequestAccessToken.findForRequest实施它,则可以使用它。

但是官方文档中提到了另一种方法:

基本上,它build议使用socketio-auth (其中“提供挂钩来实现socket.io中的身份validation,而不使用querystrings发送凭据,这不是一个好的安全做法”),并直接使用AccessToken模型。

我把这里的代码简化了一下:

在服务器端:

 app.io = require('socket.io')(app.start()); require('socketio-auth')(app.io, { authenticate: function (socket, value, callback) { var AccessToken = app.models.AccessToken; //get credentials sent by the client var token = AccessToken.count({ userId: value.userId, id: value.id, }, callback); } }); 

在客户端:

 socket.on('connect', function() { // You should have retrieved tokenId/userId by calling user.login and // saving it in cookies or localStorage. socket.emit('authentication', {id: tokenId, userId: userId }); });