ActionCable.server => 仅在 authenticated_rooth_path 内的“/cable”

ActionCable.server => ' /cable' within authenticated_rooth_path only

考虑以下场景:

1) WebSocket 验证连接。

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

2)连接建立后,通知用户

  connected: ->
    $("body").append("<div class='connection ok'>Connected.</div>")

3) 连接丢失时,通知用户

  disconnected: ->
    $("pop-up").append("<div class='connection'>Offline, trying to reconnect...</div>")

4) 当用户登出时.....

An unauthorized connection attempt was rejected
###User is now informed connection is lost. Which should not happen.

我的问题: 怎么改:

  mount ActionCable.server => '/cable'

只在范围内工作:

 authenticated :user do
   root 'users#index', as: :authenticated_root
 end

备选方案

An unauthorized connection attempt was rejected

...在您的 connection.rb 中调用 reject_unauthorized_connection 时发生。

  • 这可能是故意的不是:

    • 删除reject_unauthorized_connection如果你想允许非签名用户订阅频道:current_user变成nil

      • 为了仍然能够识别用户,您可以添加另一个标识符 (:session_id):

        module ApplicationCable
          class Connection < ActionCable::Connection::Base
            identified_by :current_user
            identified_by :session_id
        
            def connect
              self.current_user = find_verified_user
              self.session_id = request.session.id
            end
        
            private
        
            def find_verified_user
              User.find_by(id: cookies.signed[:user_id])
            end
        # ...
        
      • 如果您需要访客和登录用户之间的进一步授权规则,您可能希望在 *_channel.rb 中而不是在 connection.rb 中编写您自己的授权。
    • 如果您只希望登录用户能够订阅您的频道,请保留 reject_unauthorized_connection