I am setting up a socket.io server to handle, well, socket requests. This is running on port 1234. This is running along side a laravel 5.1 application. Laravel is using redis to handle sessions.
I have plenty of tutorials on hooking up laravel with socket.io, it’s all pretty straight forward. I can connect, respond and forward messages back down the socket and to the laravel application.
However every tutorial avoids the auth part of this setup. Once the message is received within the socket:1234 space, how do I forward that message through to laravel while making sure that request is auth’ed.
Ideally I would simply share the session, and verify the XSRF token. Because the two applications are on different ports, I can’t pick up the session directly.
Currently I am using an alternative approach, it involves the following:
- Upon socket connection (in node), I decrypt the cookie sent up on connection using node’s Crypto library and node’s PHPUnserialise library.
- This gives me the laravel session id (from the cookie)
- I use this to access the redis laravel session
- I then decrypt that session, which in turn, gives me access to the user id
It works, but I feel it could be potentially be a security hole, because I am not actually using _token to verify the origin.
I think your code is the right, and maybe the only way to do it.
A session_id is usually stored in the cookie, and at some point has to be sent to the server. Since node and php are different languages, they cannot share a session directly. You always need a intermediate storage like redis, mysql or filesystem. And of course a way to retrieve the session. The key to retrieving a session is of course the session_id.
An interesting post about securing websockets:
What he suggests is to add a random generated key to your session, that you can verify when you the websocket connection is established.
The session_id itself is already random, but these session_id’s are usually long-lived, so a short-lived random id could increase security. Short-lived should be as short as possible: let php add it to the database, and once the connection is verified in node, remove it from the database, so you cannot use it again.
There are lots of additional session verification techniques, like checking the browser string, or fixating a session to one ip adress:
I would not recommend these type of checks, as they don’t really add much extra security, only annoyance with the end user.
Most importantly i think is that:
- You use a secure way of communicating session_id etc. This means HTTPS
- Sessions should expire when the user closes their browser
- User should be notified if he connects from a different location, or should have access to his “login log”
I had found a good solution for this about a year ago. I decided to make it a module, its really easy to use. helps you get the cookie without hard coding it. helps you get that session Id and retrieve it from mysql and redis