Laravel Ratchet socket Auth

2019-07-21 00:07发布

问题:

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.

回答1:

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



回答2:

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



回答3:

Use laravel-ratchet package.

It will handle connection to auth conversion and laravel session for you.