skip to Main Content

I am making a chat application and I want people to be able to use specific usernames. I saw https://npmjs.com/socket.io.users, however, the last publication was 8 years ago. I also don’t know how to really use socket.id to check for a username, since there is no identifiable information for the username, and the id changes for each socket/refresh.

How do I get the username of the person sending the message from the server side? I do not want to send it with the client side because I think that would be quite easy to bypass and send a message as any user, though it doesn’t have to be insanely secure.

Sorry if this has been said before, everywhere I have checked talks about socket.id, but I don’t think that can check what user is sending a message.

2

Answers


  1. I suggest using one of the tutorials from https://socket.io (https://socket.io/get-started/chat) instead of an 8-year-old tutorial. This tutorial includes a username input dialog and features messages being sent with their username as the prefix.

    Login or Signup to reply.
  2. In the chat application, you need to check each user if it is authenticated to send any message. so you could write a middleware on the server and attach the new property to the socket. Depending on your authentication mechanism you write a different logic but i will demonstrate on authentication by jwt.

    const socketMiddleware = (socket, next) => {
      const token = socket.handshake.auth?.token;
      try {
        const decoded = jwt.verify(token, YOUR_TOKEN_KEY);
        // decoded is the full jwt object. you could even destructure 
        socket.user = decoded;
      } catch (err) {
        const socketError = new Error("NOT_AUTHORIZED");
        return next(socketError);
      }
      next();
    };
    

    you need to register this middleware to the io not to the express

    const socketMiddleware = require("./middleware/authSocketMiddleware");
    
    const io = require("socket.io")(server, {
        cors: {
          origin: "*",
          methods: ["GET", "POST"],
        },
      });
    
    io.use((socket, next) => {
        socketMiddleware(socket, next);
      });
    

    Now on the server, if user is authenticated, you have socket.user object. depending on how you constructed the user object in jwt, you could use socket.user.user_id or socket.user.username

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search