1

Okay so, I have a chat app made with socket.io and NodeJS.

The username is set via the value of an HTML object so that the user cant change the username.

But problem is, the user can create a connection with the socket io server and still send messages with another username if they paste this in the dev tools:

var socket = io.connect('http://*.*.*.*:3000'); socket.emit('send', { message: 'message', username: 'user' });

How can I get the node server to only accept connections from the server so that users cant execute the code above.

I hope I was clear enough. Thanks.

R N
  • 13
  • 2
  • 2
    _The username is set via the value of an HTML object so that the user cant change the username._ They can press F12 and manipulate that easily – baao Mar 30 '17 at 19:10
  • The question I think you are asking is different than what I expected from the title. Do you want to restrict access to node from other IPs (i.e. devices), or do you want to not allow a socket.io session unless the user has come through your web interface. Two very different things. – barry-johnson Mar 30 '17 at 19:13
  • I think that what you really want is one connection per IP, right? – Diego ZoracKy Mar 30 '17 at 19:14

1 Answers1

0

Deny nodejs connections from IPs that arent the server IP

If you deny connections from IPs that aren't the server's IP then you will deny connections to all of your users, because every one of them - no matter if they use their own username or a username of someone else - is connecting to your server from their browser and thus their own IP address.

The username is set via the value of an HTML object so that the user cant change the username.

Anyone can change it very easily. Just right-click on the page and click Inspect and you can change any HTML you want.

You need to authenticate users and not rely on them being who they say they are. For example you can use something like passport.socketio to access Passport.js authenticated user information from Socket.io connection - see:

I don't know if you're using Passport.js for authenticating users or not. Hopefully you use something for authentication but it's not clear from your question. You can find more info at:

It has great documentation.

Now, that having been said, if you still want to deny connections from IPs that aren't the server's IP then you can do something like this - in your connection handler:

io.on('connection', socket => {
  if (socket.handshake.address !== YOUR_SERVER_IP) {
    socket.disconnect();
  }
  // your normal code here
});

How can I get the node server to only accept connections from the server so that users cant execute the code above.

The above will do the trick but I doubt anyone will be able to use your service then.

rsp
  • 107,747
  • 29
  • 201
  • 177