Laravel Ratchet socket Auth

有些话、适合烂在心里 提交于 2019-12-12 18:19:47

问题


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.



来源:https://stackoverflow.com/questions/34762684/laravel-ratchet-socket-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!