发送 auth_token 到 ActionCable 进行身份验证

2024-01-18

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

    def connect
      #puts params[:auth_token]
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.name
   end

  end
end

我不使用网络作为操作电缆的端点,所以我想使用 auth_token 进行身份验证。默认情况下,操作电缆使用会话用户 ID 进行身份验证。如何将参数传递给连接方法?


我设法将我的身份验证令牌作为查询参数发送。

在我的 javascript 应用程序中创建消费者时,我在电缆服务器 URL 中传递令牌,如下所示:

wss://myapp.com/cable?token=1234

在我的电缆连接中,我可以得到这个token通过访问request.params:

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

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.name
    end

    protected:
    def find_verified_user
      if current_user = User.find_by(token: request.params[:token])
        current_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

这显然不理想,但我认为您不能在创建 websocket 时发送自定义标头。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

发送 auth_token 到 ActionCable 进行身份验证 的相关文章

随机推荐