【问题标题】:How to reject non-authenticated users from PHP Ratchet WebSocket?如何从 PHP Ratchet WebSocket 拒绝未经身份验证的用户?
【发布时间】:2016-10-21 13:28:34
【问题描述】:

我正在使用这个捆绑包将 Ratchet websocket 集成到我的 Symfony2 项目中:https://github.com/GeniusesOfSymfony/WebSocketBundle

我正在开发一个聊天应用程序。我遇到的问题是如何限制登录用户访问聊天?

websocket 基于 WAMP PubSub 协议。我在 ChatTopic 类中的 subscribe 方法如下所示:

public function onSubscribe(ConnectionInterface $connection, Topic $topic, WampRequest $request) {
    $email = $this->clientManipulator->getClient($connection)->getUsername();
    $user = $this->userRepository->getByEmail($email);
    $msg = array();
    $msg["type"] = "userJoined";
    $msg["displayName"] = $user->getDisplayName();
    $topic->broadcast(['msg' => json_encode($msg)]);
}

如您所见,我设法在我的 websocket 中获取用户会话并从数据库中获取所有用户数据。 我只是不知道如何防止未经授权的用户订阅聊天。

【问题讨论】:

  • 我认为您可以使用 $connection->close() 关闭该用户的连接。

标签: php symfony websocket ratchet


【解决方案1】:

使用$connection->close() 不可靠,因为客户端可能会重新连接,在这种情况下仍会订阅该主题。

我建议您使用$topic->remove($conn)。如果您检查此 link 上的代码,您将看到它实际上从订阅者中删除了当前的 $conn 对象,因此当调用 broadcast() 时,消息不再到达该客户端。

唯一的问题是客户端仍然可以发布到该主题(尽管它无法从该主题获取消息),但这可以通过在onPublish() 方法中添加以下条件来防止:

public function onPublish(\Ratchet\ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {

if (!$topic->has($conn)) {

 // user is not allowed to publish to this channel - throw exception etc.

} else {

  // user is allowed to publish

  ...
  $topic->broadcast(...);
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 2016-01-17
    • 1970-01-01
    • 2017-09-11
    • 2020-09-24
    • 1970-01-01
    • 2015-05-19
    相关资源
    最近更新 更多