I'm trying to send userid from client side to server via socket io query string on the fly:
var socketio = io.connect(8080, {query : 'userid=100'});
And on server side, I use this id for authentication.
However, I'm a little worried about this. I thought that some malicious users may change userid and send to server their own id.
Am I thinking right? What should I do in this case?
Related
I have created a flask website with python. Now, I'm trying to implement some WebRTC/PeerToPeer functionality. I have managed to connect the two peers by manually copy/pasting the SDP back and forth between them using input fields. Everything is working as supposed.
In stead of manually copy/pasting the SDP back and forth, I want to send the SDP through a websocket from the (vanilla) javascript client side to the python backend. However, this is causing me some issues.
I'm not sure I totally understand how the communication between sockets work (I'm fairly new in that field). The code below is my python server.
import socket
import threading
HEADER = 8192
PORT = 3000
SERVER = '{PRIVATE IP ADDRESS}'
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!DISCONNECT'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f'[NEW CONNECTION] {addr} connected.')
connected = True
while connected:
msg = conn.recv(HEADER)
print(f'[{addr}] {msg}')
conn.close()
def start():
server.listen()
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f'[ACTIVE CONNECTIONS] {threading.activeCount() - 1}')
if threading.activeCount() - 1 == 0:
break
start()
In the javascript on the client side, all I do is initialize the websocket using the same IP and port as the server is running on. When I refresh the client html page in the browser, the client socket is sending a message to the server. However, I'm not able to decode this message with utf-8 because of a wrong startbyte or something. I have read that sockets might use different protocols. Does that have anything to say in this case? Also, the javascript websocket never changes readystate from 0 to 1, so it never actually connects.
Am I missing something? Is there an easier or better way to connect the javascript client with the python server?
I have a project right now, but i cannot figure out how i can remove session and req.user from the client side.
I know that in node js/express js you do req.logout() and req.session = null, but that only removes it in the backend side. I am currently using react and it does not work when i call the api for removing the session.
Any idea?
the session cookies is session.sig and session
when client(typically browser)visit a web server(like nodejs based server you used), a session was built between client and server. As far as i know, session stores on the server side, normally it will send back the session's id(named sessionId or jsessionid ...), then web connection was built.
So if you would like to remove a session on the client side, you just need to remove the sessionId attribute's value in the cookie with this
document.cookie = "sessionIdKey=;"
you should replace 'sessionIdKey' with the key in your chrome dev tools => application => cookies => sitecookie place
this will end session connection, when this session time out, server will delete the session finally.
update: if you'd like to delete all cookies(sessionid between them), reference this: Clearing all cookies with JavaScript
I have a javascript GameClient that uses SocketIO to send messages to a nodeJs server. Multiple users can open the GameClient separately and send messages to the server.
GameClient
GameClient ---> NodeJS Server
GameClient
The server can send messages to specific clients using io.to(socketid).emit(). The code looks something like this:
CLIENT
this.socket = io({ timeout: 60000 })
this.socket.on('connect', () => Settings.getInstance().socketid = this.socket.id)
this.socket.on('reconnect', (attemptNumber:number) => console.log("reconnecting..."))
const json = JSON.Stringify({socketid:this.socket.id, name:"Old Billy Bob"})
this.socket.emit('user created', json)
SERVER (simplified for clarity, just keeping track of one user here)
user = {}
io.on('connection', (socket) => {
console.log('new connection')
socket.on('disconnect', () => {
console.log('user disconnected')
});
socket.on('user created', (json) => {
user = JSON.parse(json)
});
});
// demo code, send a message to our user
io.to(user.socketid).emit("message to one user")
PROBLEM
When the client browser tab becomes inactive for any reason at all, the client disconnects and reconnects and gets a new socket connection ID. This actually happens a lot in Chrome and Safari.
The server only knows the old connection id, so now it can't send direct messages any more. How do I keep the socket connection id synchronised on the client and server?
Since the server also gets a reconnected event, how does it know which user reconnected?
The answer to your question is quite simple: you need a way to identify who is who. And that is not socket.id because this only identifies sockets, not users, as you've already noticed.
So you need some authentication mechanism. Once a user authenticates you can reuse his true id (whether it is simply a name or an integer in a database is irrelevant). And then on the server side you keep a collection of pairs (true_id, socket_id). And whenever a message comes to that user, you broadcast it to all matched socket.io objects.
Edit: So here's the flow:
Client authenticates with the server, the server sends him his own true_id, which the client stores somewhere. The client may also store some session_id or maybe some other mechanism that will allow him fast reauthentication in case of disconnection (note: do not store credentials, its a security issue).
The server keeps track of (true_id, socket_id) pairs in the form of a double way, mutlivalue map (it's an implementation detail what kind of data structure should be used here, maybe two {} objects is enough). If a connection dies then (true_id, socket_id) entry is removed. Note that for a given true_id there still may be some other socket_id alive. And so it doesn't mean that the user disconnected. It only means that this particular channel is dead.
Users don't care about socket_id, they only care about true_id. What you emit is {target_id: true_id, ...} instead of {target_id: socket_id, ...} on the client side, when you want to send a direct message.
When the server receives such message with true_id inside, it retrieves all (true_id, socket_id) pairs and passes the message to all of these sockets (note: maybe you don't even need socket_id, you can simply store socket objects here). Although this is a business logic: do you allow multiple connections per user? I would. There are many edge cases here (like for example a client thinks that he disconnected, but the server thinks he is still connected, etc) and making this 100% correct is unfortunately impossible (due to the nature of networking). But with a bit of effort it is possible to make it work 99% of the time.
If a connection dies then it is your client's responsibility to automatically reconnect and reauthenticate. New socket_id for old true_id is generated on the server side.
Let me emphasize this again: clients don't care about socket_id at all. Because that doesn't identify them. This only identifies a channel. And only the server cares about this information.
I want to communicate between server and client using mosca.At first case i subscribe and publish data from client.And receive that data into server.But i face some problem again i want publish the data from server and receive that data from same client.
Example: From front-end send same data to the server.After receiving those data i want store those data in database.After save the data i want send the some response(data) to the same client using Mosca(in Javascript).
Thanks for giving answer.
If you trying to use a MQTT client on browser you should use a option to activate websocket.
Something like this:
const mosca = require("./");
const server = new mosca.Server({
http: {
port: 3000, //use this port to connect
bundle: true,
static: './'
}
});
I'm writing a node.js app, that can generate url's like this:
http://examle.com/?param1=val¶m2=val
I wonder if users will follow this urls to my app - is this possible to get params from this url and pass it to socket.io socket object that represents connection with user that was brought to site by that url.
I.E.:
user followed this url;
node.js express server handles that url and get the query params from it;
Now I want to pass these params back to user but with socket.io emit(), not to whole sockets but only to user that was brought by url.
Is this goal achivable?
Should I use some id that will be passed with url and along socket.io handshake process and than store socket in array with id as key, to get this socket later in get request of express server?