Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

user authentication using socket.io

I've red this tutorial: http://howtonode.org/socket-io-auth. It shows how to authenticate users using express and socket.io. But is there a way to authenticate users using only socket.io without the need for express?

edit:

For session handling I use RedisStore (https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO). Whats left is a module to create authentication cookies. Does anyone know of a socket.io implementation I can use to create an authentication cookie like you can do with session handling?

like image 690
bekite Avatar asked Oct 23 '13 17:10

bekite


2 Answers

I know this is bit old, but for future readers in addition to the approach of parsing cookie and retrieving the session from the storage (eg. passport.socketio ) you might also consider a token based approach.

In this example I use JSON Web Tokens which are pretty standard. You have to give to the client page the token, in this example imagine an authentication endpoint that returns JWT:

var jwt = require('jsonwebtoken');
// other requires

app.post('/login', function (req, res) {

  // TODO: validate the actual user user
  var profile = {
    first_name: 'John',
    last_name: 'Doe',
    email: '[email protected]',
    id: 123
  };

  // we are sending the profile in the token
  var token = jwt.sign(profile, jwtSecret, { expiresInMinutes: 60*5 });

  res.json({token: token});
});

Now, your socket.io server can be configured as follows:

var socketioJwt = require('socketio-jwt');

var sio = socketIo.listen(server);

sio.set('authorization', socketioJwt.authorize({
  secret: jwtSecret,
  handshake: true
}));

sio.sockets
  .on('connection', function (socket) {
     console.log(socket.handshake.decoded_token.email, 'has joined');
     //socket.on('event');
  });

The socket.io-jwt middleware expects the token in a query string, so from the client you only have to attach it when connecting:

var socket = io.connect('', {
  query: 'token=' + token
});

I wrote a more detailed explanation about this method and cookies here.

like image 129
José F. Romaniello Avatar answered Sep 19 '22 17:09

José F. Romaniello


Instead or wiring up authentication and session handling code manually, I'd recommend to go with a dedicated module, such as session.socket.io (but please note that this is a module that requires Express as well).

I guess (but don't know) that there were downvotes because you need some sort of session handling, and you most probably do not want to do this manually as well ;-). Hence it's a quite good idea to stick with Express here.

Nevertheless, it's an interesting question, although I can not answer on how to do it without Express.

like image 32
Golo Roden Avatar answered Sep 18 '22 17:09

Golo Roden