Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticating socket io connections using JWT

People also ask

Does socket.io need authentication?

It is important to know that, by default, there is no authentication provided by Socket.io connections. Anyone can point a client at your server and start emitting and receiving events.

What is passport JWT?

A Passport strategy for authenticating with a JSON Web Token. This module lets you authenticate endpoints using a JSON web token. It is intended to be used to secure RESTful endpoints without sessions.

How do I use socket.io middleware?

If you want middleware to process an incoming http request, use Express middleware with app. use() . If you want middleware to process an incoming socket.io connection, use socket.io middleware with io. use() .


It doesn't matter if the token was created on another server. You can still verify it if you have the right secret key and algorithm.

Implementation with jsonwebtoken module

client

const {token} = sessionStorage;
const socket = io.connect('http://localhost:3000', {
  query: {token}
});

Server

const io = require('socket.io')();
const jwt = require('jsonwebtoken');

io.use(function(socket, next){
  if (socket.handshake.query && socket.handshake.query.token){
    jwt.verify(socket.handshake.query.token, 'SECRET_KEY', function(err, decoded) {
      if (err) return next(new Error('Authentication error'));
      socket.decoded = decoded;
      next();
    });
  }
  else {
    next(new Error('Authentication error'));
  }    
})
.on('connection', function(socket) {
    // Connection now authenticated to receive further events

    socket.on('message', function(message) {
        io.emit('message', message);
    });
});

Implementation with socketio-jwt module

This module makes the authentication much easier in both client and server side. Just check out their examples.

client

const {token} = sessionStorage;
const socket = io.connect('http://localhost:3000');
socket.on('connect', function (socket) {
  socket
    .on('authenticated', function () {
      //do other things
    })
    .emit('authenticate', {token}); //send the jwt
});

Server

const io = require('socket.io')();
const socketioJwt = require('socketio-jwt');

io.sockets
  .on('connection', socketioJwt.authorize({
    secret: 'SECRET_KEY',
    timeout: 15000 // 15 seconds to send the authentication message
  })).on('authenticated', function(socket) {
    //this socket is authenticated, we are good to handle more events from it.
    console.log(`Hello! ${socket.decoded_token.name}`);
  });