1

I'm new to web sockets (specifically to socketIO interfaces, both client and server), and I wonder how basic JWT auth is usually implemented. How the headers are passed through. Should I add them to every socket listener or emit event? Or just once during the connection. Maybe the connection is already considered private because of the connection id?

I am using Socket.io-client v.4 and flask-socketio. I am interested in general practices and would be grateful for any information or your own experience.

Yewgen_Dom
  • 66
  • 6

1 Answers1

4

There are many ways to pass authentication when you connect:

  • HTTP header
  • Cookie
  • query string
  • auth option

To pass a token in a header (not valid when connecting directly via WebSocket):

const socket = io({
  extraHeaders: {
    "Header-Name": "abcd"
  }
});

Same site cookies are always passed to the server. To pass cookies cross-site:

const socket = io("https://my-backend.com", {
  withCredentials: true
});

To pass it in the query string:

const socket = io({
  query: {
    token: 'abcd'
  }
});

To pass it with the auth option (Socket.IO v3 and up only):

const socket = io({
  auth: {
    token: "abcd"
  }
});
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152