1

I am creating a website that is built on PHP. It has a small page where users can have a group chat and message each other. For that page I open a websocket with a help of socket.io and expressjs. I want to use usernames that people registered with. And, of course, I want people not be able to impersonate other people. So, once user enters a message, it gets socket.emited to the server, and from the server I do something like:

socket.on('message', function(msg) {
    io.emit('message', {
        username: username
        message: msg
    });
});

To broadcast that message to everyone.

My question is, how do I retrieve the username? My solution at the moment is this. I create a unique 128 chars long user_id on user sign up, store in redis something like

user_id: username,

and then I pass user_id on socket.emit and do on Node server

username: redisClient.get("user_id").

Is it a good idea? Is it secure? Or there are better solutions to this problem?

1 Answer 1

2

From my perspective your case fits very well with JSON Web Token (JWT) approach. You can encode all necessary data in JWT and pass it with requests. Your Node.js application should verify signature of JWT and extract all needed data from it. If something is too big / complex to put in JWT, than backend application may request for this data another backend service for it via your backend network security mechanisms.

5
  • Thanks for the reply, but from my understanding of JWT, wouldn't people be able to decode the string I pass from PHP service, add any username (or other data) to it, encode it, and pass it to my Nodejs server? Then they could impersonate any user.
    – evening
    Aug 19, 2018 at 15:57
  • Oh, although I can see we can provide secret key it seems, then it would be a perfect solution!
    – evening
    Aug 19, 2018 at 16:00
  • To protect against that JWT is being signed by entity which creates it. In your case PHP application will issue JWT, sign it and sent to client. Client then will send it to Node.js application. Node.js will first check signature. Check will not pass if client alters JWT. Aug 19, 2018 at 16:02
  • I am able to decode the jwt token with jwt.calebb.net, even though I add a key generating the jwt token. Any ideas why? I thought you need a secret key to decode the data.
    – evening
    Aug 19, 2018 at 16:13
  • It can always decoded, but successful verification can be done only when secret key is known in Node server, right?
    – evening
    Aug 19, 2018 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.