Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Websocket with Passport

How do I access the passport login for the current session when someone opens a WebSocket connection?

I've found a nice project express-ws which seems to work beautifully

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

But how would I go about getting this same information with a plain Websocket connection?

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);
    });
});

(this second connection does work just fine - but I can't for the life of me find any way to get the logged in info from Passport)

like image 809
Adam Rackis Avatar asked Feb 26 '16 14:02

Adam Rackis


1 Answers

When you're creating your WS server, add a "verifyClient" parameter as follows to grab the session information:

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

Where sessionParser is your express-session configured object. This then allows you to access it within the websocket via req.session. If you're using passport, you might want req.session.passport.user..

like image 128
Alexander Craggs Avatar answered Oct 22 '22 15:10

Alexander Craggs