Socket.io and node.js Passport Authentication

Authenticating socket.io with passport is tricky because socket.io doesn't have direct access to the cookie data that passport.js and express create. The solution is to add a socket.io function that requests the cookie and checks it against the list created by passport. Fortunately jfromaniello on github has already created passport.socketio.

Install passport.socketio with npm install passport.socketio, of course you'll also want to have passport and express installed. Then in your main program add the authentication function to your sockets. The readme file on the github page shows the exact code. The only issue I ran into was not using the same IP address on both the client side and server side. Make sure that you use the IP address 127.0.0.1:8080 instead of localhost:8080 on both sides of the connection and in the web browser, otherwise the cookie may not get sent.

Read More