Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Socket.io client authentication using Laravel session data

I want to authenticate socket.io clients based on client session data created by Laravel.

What I have thought of is :

A - emitting username and email from client to server;

B - storing the data my socket.io server needs in Redis in php after user logs in and then reading it in Node.js based on session cookie id. I will probably have to store sessionId -> "email, name" in Redis if I prefer this approach.;

C - using Redis session driver in Laravel, decoding cookies set by Laravel, accessing Laravel session values from Node.js, unserializing and decoding them;

Approach A is obviously very insecure and could be used only to prove concept.

Approach C seems better since I do not have to duplicate or manage session data but only to decode it. This way however couples my application to the implementation details of Laravel managed sessions and thus doesnt seem to be appropriate.

Approach B looks more promising and it is simpler to implement. However using approach B means I have to manage some session data myself in order for socket.io to be able to read it. Doing so may make Laravel session data and session data I store in Redis mutually inconsistent and this will happen at some point in the time. In some extreme case for example an expired session id could be reused and some socket.io client will be authenticated incorrectly as another user. I cant think of more trivial case at this moment but because of this incosistency I assume its possible that there is such case and both security and UX could be compromised.

What is a more elegant, robust and secure way to achieve user authentication based on Laravel session data in socket.io application? If there are no drastically better approaches and I assume approach B is best what could I do to improve consistency between session data I manage using Redis and Laravel session data.

The whole point as far as I can summarize is actually accessing Laravel session data outside Laravel and php and identifying clients by sessionId, email and username.

like image 710
Boris D. Teoharov Avatar asked Jul 05 '15 18:07

Boris D. Teoharov


1 Answers

I suggest you to use JSON Web Token authentication.

JSON Web Token (JWt) is a relatively new token format used in space-constrained environments such as HTTP Authorization headers. JWT is architected as a method for transferring security claims based between parties. More detailed info about JWT

The easiest way to do this with Laravel is by a using a package like this one. Or you can implement it by yourserlf.

Using JWT auth you will be able to access the user from the token. For example:

$user = JWTAuth::parseToken()->toUser();

For detailed information about how to use 'jwt-auth' take a look here.

like image 72
Alex Kyriakidis Avatar answered Oct 19 '22 22:10

Alex Kyriakidis