I am starting learning Ratchet (reactPHP) I am using laravel. But I came to a line about security.
How can I deny websocket connection based on user is logged in or not
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
$this->users[$conn->resourceId] = $conn;
if(Auth::check()){
echo 'user logged in';
}else{
echo "New connection! ({$conn->resourceId})\n";
}
}
I used something like this but it passes the Auth::check and console always shows New Connection.
Ok Playing around found solution and it seems ok:
I am using Sentinel
$session = (new SessionManager(App::getInstance()))->driver();
$cookies = $conn->WebSocket->request->getCookies();
$laravelCookie = urldecode($cookies['timeline_auth']);
$idSession = Crypt::decrypt($laravelCookie);
$user = Sentinel::findByPersistenceCode($idSession);
If there is better solution please leave a comment
You cannot use Auth::user() anymore with WebSocket. The WebSocket server is handling multiple connections (so Auth::user() dosent have any sense). BUT you can access the user session.
more details here
https://laravel.io/forum/01-16-2015-loading-laravels-session-using-ratchet
Use laravel-ratchet package.
It will handle connection to auth conversion and laravel session for you.