5

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

我想使用环回身份验证方法对 socket.io 进行身份验证。

我在 loopback/lib/middleware/token.js 中找到了对用户进行身份验证的方法。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)

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

4

1 回答 1

1

好吧,我相信 Loopback 令牌是为与快速请求对象一起使用而构建的。在最新版本(2.x)中,如果您AccessToken.findForRequest自己覆盖并实现它,您可以使用它。

但是官方文档中涵盖了另一种方法:

基本上它建议使用socketio-auth(其中“提供挂钩以在 socket.io 中实现身份验证而不使用查询字符串发送凭据,这不是一个好的安全实践”)并直接使用 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 });
});
于 2016-11-26T13:07:58.427 回答