How to authenticate socket.io connections using JWT?

Sometimes, we want to authenticate socket.io connections using JWT.

In this article, we’ll look at how to authenticate socket.io connections using JWT.

How to authenticate socket.io connections using JWT?

To authenticate socket.io connections using JWT, we send the token with the socket.io client.

And then on the server, we check the token.

For instance, we write

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

to call io.connect to connect to the server.

We set the query.token property to send the auth token.

Then on the server, we write

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

io.use((socket, next) => {
    if (socket.handshake?.query?.token) {
      jwt.verify(socket.handshake?.query?.token, 'SECRET_KEY', (err, decoded) => {
        if (err) {
          return next(new Error('Authentication error'));
        }
        socket.decoded = decoded;
        next();
      });
    } else {
      next(new Error('Authentication error'));
    }
  })
  .on('connection', (socket) => {
    socket.on('message', (message) => {
      io.emit('message', message);
    });
  });

to get the token with socket.handshake?.query?.token.

If it’s present, we check it with the jwt.verify method from the jsonwebtoken package against the private SECRET_KEY.

If auth is successful, err is null. And we call next with nothing.

Otherwise, we throw an error if the token isn’t present or when err is set.

Next, we call on with 'connection' to emit a message when connection succeeds.

Conclusion

To authenticate socket.io connections using JWT, we send the token with the socket.io client.

And then on the server, we check the token.