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.