I\'m trying to create a private messaging system using socket.io
In order to associate the users with their sockets, most sites are suggesting something like this:
I would use jsonwebtoken
and socketio-jwt
modules for solving this security issue.
Server:
var secret = 'shhhhhh';
app.get('/getJWT', function(req, res) {
/* Do your authentication here using header and get the userId */
var userId = 'someId';
var jwt = require('jsonwebtoken');
var token = jwt.sign({ 'userId': userId }, secret);
res.json({
token: token
});
});
var socketioJwt = require('socketio-jwt');
io.use(socketioJwt.authorize({
secret: secret,
handshake: true
}));
io.sockets.on('connection', function (socket) {
var userId = socket.decoded_token.userId;
/* your logic */
Client:
var token = "token you got from the /getJWT"
var c = io.connect('http://localhost:3000/', { query: "token=" + token });
As the token is encoded with a secret, client cannot change and send it.
Refer this article to know why this is better.