【问题标题】:ActionCable - failed to upgrade to WebSocketActionCable - 升级到 WebSocket 失败
【发布时间】:2017-01-19 04:45:05
【问题描述】:

我在连接到 Web 套接字时遇到问题。有一个错误:

Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]]
An unauthorized connection attempt was rejected
Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2016-09-11 18:57:49 +0200
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2016-09-11 18:57:49 +0200

连接.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', "User #{current_user.id}"
    end

    protected

    def find_verified_user
      if verified_user = User.find_by(id: cookies.signed[:user_id])
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

我找到了一些我应该使用config.allowed_request_origins 的解决方案,但它并没有解决我的问题。我通过添加此方法尝试使用 session_helper:

def set_cookie(user)
  the_username = user.username.to_s
  cookies.permanent.signed[:username] = the_username
end

没有什么能解决我的问题。

更新: 我看到这个问题是 cookies.signed[:user_id] 为零。你有什么建议是什么原因造成的?我使用标准 URL 和端口进行测试(localhost:3000)。

【问题讨论】:

  • 在我的日志中看到相同问题的相同错误后,这篇 SO 帖子帮助我解决了我的问题。 stackoverflow.com/questions/38719359/…。只需在config/environments/development.rb 中设置config.action_cable.allowed_request_origins 与您将允许通过websockets 连接到您的应用程序的主机。

标签: ruby-on-rails websocket actioncable


【解决方案1】:

我使用env['warden'].user 解决了我的问题。下面是更新的方法。

   def find_verified_user
      (current_user = env['warden'].user) ? current_user : reject_unauthorized_connection
   end

【讨论】:

  • 这还不够。这样,您只需在用户登录时删除错误。但如果用户未登录 - 错误仍然存​​在。这是因为 App.room = App.cable.subscriptions.create "RoomChannel" 调用 inside room.coffee (或在您的代码中类似)。解决方案是根据用户是否登录有条件地渲染room.coffee - 但这需要从资产中排除room.coffee - 及其单独的渲染(因为如果用户登录,您不能有条件地渲染js进/出)。
【解决方案2】:

在对您的代码进行任何更改之前,只需停止 rails 服务器并执行捆绑安装然后重新启动。也许该问题将得到解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-03
    • 2017-04-09
    • 1970-01-01
    • 2018-10-30
    • 2018-11-26
    • 1970-01-01
    • 2016-11-07
    • 2018-11-29
    相关资源
    最近更新 更多