How should I set the real IP address when using CloudFlare, Heroku, and RoR?

这一生的挚爱 提交于 2019-12-05 13:40:43

You can use the Rack middleware from the remote_ip_proxy_scrubber gem to make sure your Rails app ignores IP addresses from trusted proxy servers like CloudFlare.

First, add the gem to your Gemfile and then bundle install

gem 'remote_ip_proxy_scrubber'

Now you'll need the updated list of CloudFlare IP addresses: https://www.cloudflare.com/ips-v4

Using that list of CloudFlare IPs, add the following to config/application.rb or conifg/environments/*.rb

# Make sure CloudFlare IP addresses are
# removed from the X-Forwarded-For header
# before our app sees them
config.middleware.insert_before(Rails::Rack::Logger,
   RemoteIpProxyScrubber.filter_middleware, 
   %w{
     199.27.128.0/21
     173.245.48.0/20
     103.21.244.0/22
     103.22.200.0/22
     103.31.4.0/22
     141.101.64.0/18
     108.162.192.0/18
     190.93.240.0/20
     188.114.96.0/20
     197.234.240.0/22
     198.41.128.0/17
     162.158.0.0/15
     104.16.0.0/12
     172.64.0.0/13
  })

# Make sure the customer's real IP address (remote_ip)
# is used in our Rails logs.
config.middleware.insert_before(Rails::Rack::Logger, RemoteIpProxyScrubber.patched_logger)
config.middleware.delete(Rails::Rack::Logger)

Tracking changes to the list of CloudFlare IPs hasn't been too problematic for our company thus far.

  1. As a CloudFlare customer, we received an email from CloudFlare before their most recent addition IP addresses
  2. There's also an IFTTT recipe you can use to get an email notification when CloudFlare adds new IP addresses.

Since Cloudflare abides to best-practices, and uses the X-Forwarded-For HTTP header, you just need to make sure to use it properly.

Specifically for rails, this has already been asked several times, such as What's the difference between request.remote_ip and request.ip in Rails?

"These ranges could change in the future, even though CloudFlare says they don't often,"

The more likely thing is that we would add new ranges to our existing ranges (we also don't use new ips for quite some time so that people can adjust to the new ranges).

"Since Cloudflare abides to best-practices, and uses the X-Forwarded-For HTTP header, you just need to make sure to use it properly."

This is also correct:)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!