Laravel 棘轮套接字认证

Laravel Ratchet socket Auth

我开始学习 Ratchet (reactPHP) 我正在使用 laravel。但我谈到了安全问题。 如何根据用户是否登录拒绝 websocket 连接

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";
        }

    }

我使用了类似的东西,但它通过了 Auth::check 并且控制台始终显示新连接。

好的 找到解决方案,似乎还可以: 我正在使用 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);

如果有更好的解决办法欢迎留言

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.

此处有更多详细信息

https://laravel.io/forum/01-16-2015-loading-laravels-session-using-ratchet

使用 laravel-ratchet 包。

它将处理与身份验证转换的连接和 laravel 会话。