- This answer on the StackOverflow question: How do I access cookie-session middleware in socket.io on NodeJS?
Last active
May 27, 2019 20:30
-
-
Save dimitrinicolas/b72120bce2d998e0c1120dd30fd7ff50 to your computer and use it in GitHub Desktop.
Express Application with Passport session reading with Socker.io
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { initWebSocketServer } = require('./init-web-socket-server.js'); | |
/** Init your Express application and listen. */ | |
initWebSocketServer(server); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const socketIo = require('socket.io'); | |
const { sessionStore } = require('./session-store.js'); | |
const { deserializeUser } = require('./user-serializer'); | |
const initWebSocketServer = server => { | |
const io = socketIo(server); | |
io.set('authorization', (handshake, callback) => { | |
/** Collect cookies from socket request headers. */ | |
const cookie = handshake.headers.cookie; | |
/** Create a fake Express request object. */ | |
const req = { headers: { cookie } }; | |
sessionStore(req, {}, () => { | |
/** Return an error if user is not authorized. */ | |
if (!req.session.passport.user) { | |
callback(new Error('Access not authorized.'), false); | |
return; | |
} | |
/** Else, put user data in socket connection handshake. */ | |
handshake.user = deserializeUser(req.session.passport.user); | |
callback(null, true); | |
}); | |
}); | |
io.on('connection', socket => { | |
/** The client will connect only if it is authorized by the authorization method. */ | |
console.log(socket.request.user); | |
}); | |
}; | |
module.exports.initWebSocketServer = initWebSocketServer; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"dependencies": { | |
"cookie-parser": "^1.4.4", | |
"cookie-session": "^1.3.3", | |
"express": "^4.17.1", | |
"passport": "^0.4.0", | |
"passport-mock-strategy": "^2.0.0", | |
"socket.io": "^2.2.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment