Where and how do you generate a JWT token when authenticating a socket.io connection with Node/React?

Viewed 975

From what I understand about Socket.io, there are multiple security issues, such as those mentioned in this stack exchange post.

For my case, I'm using socket.io in Node and socket.io-client for React, and setting up a nice line of communication, however I don't need any login from the client side, since I'm simply querying an external API from the backend and posting results to the front end. So I've decided to use the package socketio-jwt to secure the connection using jwt tokens.

To implement, the documentation contains the following example to use jwt authentication:

Server Side

io.use(socketioJwt.authorize({
  secret: 'your secret or public key',
  handshake: true
}));
 
io.on('connection', (socket) => {
  console.log('hello!', socket.decoded_token.name);
});

Client Side

const socket = io.connect('http://localhost:9000', {
  extraHeaders: { Authorization: `Bearer ${your_jwt}` }
});

My question is this: on the client side where does the variable your_jwt come from and how can I generate it?

2 Answers

The token needs to be generated by the login API. The user sends username and password to a login endpoint and then your server returns the JWT.

Now, what is this login API?

Most API server implements an HTTP endpoint (POST /login). Then the client can save it in local storage.

If your app doesn't have an HTTP server to support you can just implement this via WebSocket.

You should have an endpoint in your Node app where you generate JWT, client side will get it from that endpoint, save it in persistent storage and reuse it.

Related