简体   繁体   中英

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

I am upgrading a Rails app to use websocket via Action Cable. For logging purposes, I need to get the client's IP address and the user agent who sends the socket message.

In the speak method of MyChannel class ( app/channels/my_channel.rb ), I cannot access the session or the request.

Do you have any idea on how I can get user_agent and the client IP address in this speak method?

您可以从 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.

For example, here is how I get the User-Agent HTTP header which was used while establishing WebSocket connection:

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

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 ). 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).

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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