【问题标题】:bind socket.io id to user id without sessions (express, passport JWT)将 socket.io id 绑定到没有会话的用户 id(快递、护照 JWT)
【发布时间】:2017-04-28 21:12:18
【问题描述】:

我正在快速开发 RESTful API,使用 JWT 和护照进行授权。我想为通知和信令目的实现 socket.io 连接(WebRTC 会话建立)。我不想实现标准会话管理,不想处理 cookie,但不知何故我必须能够通过套接字寻址特定用户。我在所有路由中都有事件处理,因此应用程序知道经过身份验证的请求和相应的用户 ID。一种方法(可能)是使用用户 ID 创建套接字 io 组,将套接字添加到该组并在那里发出。 (在每个后续请求中进行重新连接处理并检查套接字是否存在——这太复杂了)。我想应该有更好的方法。我也使用 Redis,所以我可以在这个方案中利用它。任何建议都值得赞赏,谢谢

【问题讨论】:

    标签: express socket.io webrtc jwt passport.js


    【解决方案1】:

    嗯,我设法以这种方式解决了这个问题。

    服务器:

    import jwt from 'jwt-simple'; //I'm using ES6/Babel
    
    module.exports = function(app)  {
    var io = app.get('io'); //Import io any possible way, 
                            //here I do it like so because I set     
                            //app.set('io', io) in my index.js
    var user_id;
    
    io.on('connection', socket => {
    
    // Recieve encoded token from client, decode and find user id
    // To do - check againt database
    socket.on('auth', token => {
      if (token) {
        var decoded = jwt.decode(token, 'secret')
        user_id = decoded.sub
        socket.emit('auth', user_id);
      }
    })
    
    // Join room proposed by client - user id string
    socket.on('room', room => {
      socket.join(room)
      console.log('Server joined room...', room)
    
      //emit message to user id from anywhere in the app
      io.sockets.in(user_id).emit('message', 'what is going on, party people?');
      })   
    
     })
    }
    

    客户:

      var token = localStorage.getItem('token');
      var socket = io(); 
    
      socket.on('connect', data => {
      socket.emit('auth', token);
      socket.on('auth', user_id => {
        socket.emit('room', user_id);
      })
    })
    

    现在,为了解决特定用户,我总是可以向房间 id 发出等于用户 id 的信息,前提是该用户已获得凭据。即使在浏览器刷新之后。

    Photo: the left client has valid token in localStorage, the right one doesn't

    【讨论】:

      猜你喜欢
      • 2012-09-27
      • 2012-05-28
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2019-07-09
      • 1970-01-01
      • 2019-10-19
      相关资源
      最近更新 更多