socketio / socket.io-protocol

Socket.IO Protocol specification
https://socket.io
506 stars 62 forks source link

socket.io unity authentication #17

Closed mahdiyaroraei closed 3 years ago

mahdiyaroraei commented 6 years ago

Can you explain what is your solution for user authentication over socket.io?

darrachequesne commented 3 years ago

Middlewares may be used for user authentication:

Client

const io = require("socket.io-client");
const socket = io({
  query: {
    token: "abcd"
  }
});
socket.on("connect", () => { /* success */ });
socket.on("error", () => { /* failure */ });

Server

const io = require("socket.io");
io.use((socket, next) => {
  if (socket.handshake.query.token === "abcd") {
    next();
  } else {
    next(new Error('invalid'));
  }
});
io.on('connect', socket => {});