I am trying to transmit a cookie back to the server, long after an authorization has occurred. The reason being I want to check if a user is still logged in after a socket has been open for a while. Is there a way to do this with socket.io? Maybe by forcing an authorization again; is this possible?
You should be able to do that by enabling the socket.io authorization. Once enabled it will call into the provided function when socket.io connects.
Here is some code I used a while ago that should get you started.
var connect = require('connect');
// these should be the same as you use for setting the cookie
var sessionKey = "yourSessionKey";
var sessionSecret = "yourSessionSecret";
socketIO.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
// if there is, parse the cookie
data.cookie = connect.utils.parseSignedCookies(cookie.parse(decodeURIComponent(data.headers.cookie)), sessionSecret);
if (!data.cookie[sessionKey]) return accept('No cookie value for session key ' + sessionKey, false);
var parts = data.cookie[sessionKey].split('.');
data.sessionId = parts[0];
// at this point you would check if the user has been authenticated
// by using the session id as key. You could store such a reference
// in redis after the user logged in for example.
// you might want to set the userid on `data` so that it is accessible
// through the `socket.handshake` object later on
data.userid = username;
// accept the incoming connection
return accept(null, true);
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
return accept('No cookie transmitted.', false);
}
});
Once you set the data
properties (e.g. data.userid
in the above example) you can access them by via the socket.handshake
object. For example:
io.sockets.on('connection', function (socket) {
var userId = socket.handshake.userid;
socket.on('reauthorize-user', function(){
// check the user status using the userId then emit a socket event back
// to the client with the result
socket.emit('reauthorization-result', isAuthorized);
});
});
On the client you would just emit the reauthorize-user
event and listen to the reauthorization-result
event. You could obviously have a setTimeout to perform the check in certain intervals.