Yewgen_Dom
Yewgen_Dom

Reputation: 100

How Auth works with SocketIO?

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.

Upvotes: 2

Views: 4548

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67479

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"
  }
});

Upvotes: 6

Related Questions