I'm using Koa, Passport.js and koa-session to authenticate users. So it basically looks like:
// session
var session = require('koa-session');
app.keys = [config.secret];
app.use(session());
// auth
require(__dirname+'/lib/auth'); // de/serializeUser, strategies etc..
var passport = require('koa-passport');
app.use(passport.initialize());
app.use(passport.session());
This works well. On requests I do have the req.user
, with the user id. But when using sockets, I can do:
io.on('connection', function(socket) {
console.log(socket.request.headers.cookie),
});
But of course it's only the encrypted session ID, how could I deserialize the user and get the user.id just like I do when I get the req.user
on get or post request?
Thank you in advance.
This is a very late response but I hope it will be of use to you. I just spent about four hours trying to solve this problem.
The first issue you will run into is that
koa-session
does not use real session stores. It embeds all information in the cookie itself and then parses it to and from the client. While this can be convenient, it works against you when trying to incorporateSocket.IO
, asSocket.IO
has no access tokoa-session
.You'll need to migrate to
koa-generic-session
and use a session store to keep track of your sessions. This is, in my opinion, a better move regardless. I am currently usingkoa-redis
for my session stores.In order to have access to your sessions in
Socket.IO
, you will need to set up a global store. Here's what my global store looks like.After that, the initial setup is easy.
Now that you have a global session storage, you can then access it in
Socket.IO
. Please keep in mind you will need to install thecookie
andco
modules.I've adjusted the code for
Socket.IO
v1. I hope this helps.I used a regex to grab the userId and found then in my database. Not the cleanest approach but it works well. I'm just using koa-session-store as my session with passport js.