Node.js chat - user authentication

I recently installed nodejs chat server, the chat client is served by php server. When users log in, their sessions will be stored in the mysql php server, and the login cookie will be added to the browser.

I want to restrict users that only registered users can communicate. What is the best practice for archiving this?

My quick thought:

When the chat client is loaded, if the user logs in, I will send cookie information to log in to verb nodejs through the socket. Then create a nodejs session. When the user chat, a message along with information about the cookies will be sent to the nodejs server through the socket. If the cookie information does not match the nodejs session, the message will not be broadcast and the client socket will be disconnected.

+7
source share
2 answers
0
source

Websocket is a permanent open connection. You only need to consult once when connecting to the web schedule.

Just send your cookie to login to node.js once and save it on the server with a link to the socket connection. Then process messages only from authenticated users and transmit them only to authenticated users.

The problem is that client-side users can easily fake this cookie as node does not talk to php to make sure it has a valid login cookie.

An example using now .

warning pseudo code

// server.js everyone.now.joinChat = function(cookie) { chat.add(this, cookie); } everyone.now.serverMessage = function(message) { if (chat.hasUser(this)) { chat.broadcast(message); } } chat = (function() { var users = []; return { "add": function(client) { users.push(client); }, "hasUser": function(client) { return users.some(function(user) { return user === client; }); }, "broadcast": function(message) { users.each(function(user) { user.clientMessage(message); }); } } }()); // client.js $(function() { now.joinChat($.cookie("login")); $("#send").click(function() { now.serverMessage($(this).data("message")); }); now.clientMessage = function(message) { $("#messages").append($("<span></span>").text(message)); } }); 
+3
source

All Articles