简体   繁体   English

Rails Action Cable:如何获取用户代理和客户端 IP 地址?

[英]Rails Action Cable: How to fetch User Agent & Client IP Address?

I am upgrading a Rails app to use websocket via Action Cable.我正在升级 Rails 应用程序以通过 Action Cable 使用 websocket。 For logging purposes, I need to get the client's IP address and the user agent who sends the socket message.出于日志记录的目的,我需要获取客户端的 IP 地址和发送套接字消息的用户代理。

In the speak method of MyChannel class ( app/channels/my_channel.rb ), I cannot access the session or the request.MyChannel类( app/channels/my_channel.rb )的speak方法中,我无法访问会话或请求。

Do you have any idea on how I can get user_agent and the client IP address in this speak method?您对我如何在此speak方法中获取user_agent和客户端 IP 地址有任何想法吗?

您可以从 Channel 所属的 Connection 对象中的请求中获取此信息。

ActionCable::Connection::Base contains all information about the current connection environment (HTTP headers, rack process, etc), and you can access it via its env attribute reader. ActionCable::Connection::Base包含有关当前连接环境的所有信息(HTTP 标头、机架进程等),您可以通过其env属性读取器访问它。

For example, here is how I get the User-Agent HTTP header which was used while establishing WebSocket connection:例如,这里是我如何获取在建立 WebSocket 连接时使用的User-Agent HTTP 标头:

user_agent = connection.env["HTTP_USER_AGENT"]

Note that I run this code from ApplicationCable::Channel instance, where connection instance is available via connection attribute请注意,我从ApplicationCable::Channel实例运行此代码,其中连接实例可通过connection属性获得

I couldn't find any documentation about it, but I believe it's safe since env attribute is made publicly available ( https://api.rubyonrails.org/v5.1.6/classes/ActionCable/Connection/Base.html#method-i-request ).我找不到任何关于它的文档,但我相信它是安全的,因为env属性是公开可用的( https://api.rubyonrails.org/v5.1.6/classes/ActionCable/Connection/Base.html#method-i -请求)。 You can get the full list of the keys that this hash contains by running connection.env.keys in console (when connection instance is available, obviously).您可以通过在控制台中运行connection.env.keys来获取此哈希包含的键的完整列表(显然,当connection实例可用时)。

要使用remote_ip助手,您可以在您的频道中执行此操作:

ActionDispatch::Request.new(connection.env).remote_ip

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM