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)
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
..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With