使用环回令牌对socket.io进行身份验证



我正在使用环回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()方法传递了错误的对象类型。

我相信Loopback令牌是为与express请求对象一起使用而构建的。在最新版本(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 });
});

相关内容

  • 没有找到相关文章

最新更新