将Websocket与Passport一起使用

时间:2016-02-26 14:19:02

标签: javascript node.js websocket passport.js

当有人打开WebSocket连接时,如何访问当前会话的护照登录?

我找到了一个很好的项目express-ws,似乎工作得很漂亮

app.ws('/', function(ws, req) {
    ws.on('message', function(msg) {
        console.log('express-ws --- ', msg);
    });
    console.log('socket', req.user); //current user == req.user
});

但是,如何通过简单的Websocket连接获取相同的信息呢?

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({ port: 3001 });

wss.on('connection', function(socket){
    //Where is the current user????
    console.log('connection');

    socket.on('message', function(message){
        console.log('message received', message);
    });
});

(这第二个连接确实运行正常 - 但我无法找到任何方式从Passport获取登录信息)

3 个答案:

答案 0 :(得分:7)

当您创建WS服务器时,添加一个" verifyClient"获取会话信息的参数如下:

  const wss = new (require('ws').Server)({
    server,
    verifyClient: (info, done) => {
      sessionParser(info.req, {}, () => {
        done(info.req.session)
      })
    }
  })

sessionParserexpress-session配置对象的位置。然后,您可以通过req.session在websocket中访问它。如果您使用的是护照,则可能需要req.session.passport.user ..

答案 1 :(得分:-1)

不是使用req.session.passport.user来访问经过身份验证的用户ID,而是可以使用ws.upgradeReq.session.passport.user

app.ws('/', function(ws, req) {
    ws.on('message', function(msg) {
        console.log('express-ws --- ', msg);
    });
    console.log(ws.upgradeReq.session.passport.user);
    /* keys can be found like
    for(var key in ws.upgradeReq.session.passport){
        console.log(key);
    }
    */
});

答案 2 :(得分:-1)

也许不是最好的解决方案,但是我们可以使用以下代码删除WS连接:


const wss = new webSocket.Server({ server, port: 9999})

wss.on('connection', (ws, req) => {

  // get token from url:  ..url..?token=your_JWT_TOKEN
  const params = require('url').parse(req.url, true).query
  const { token } = params

  // add token to headers (could be done on frontend)
  req.headers.authorization = `Bearer ${token}`

  // look for the user with token
  passport.authenticate(
    'jwt',
    {
      session: false
    },
    (err, user, info) => {
      // If no user close websocket
      if (!user) {
        console.log('Websocket disconnected due to invalid token')
        ws.close()
      }
    }
  )(req)