Forked from mrk21/config-initializers-trusted_proxies.rb
Created
November 6, 2023 07:48
-
-
Save ZilvinasKucinskas/72d6b1b0414b1bcc8c5cf744e368405e to your computer and use it in GitHub Desktop.
How to get a remote ip on CloudFront + Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @see https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/LocationsOfEdgeServers.html | |
# @see https://morizyun.github.io/ruby/rails-controller-get-ip.html | |
# @see https://dev.classmethod.jp/cloud/aws/get-ec2-public-ip-range-by-powershell/ | |
# @see https://github.com/rails/rails/blob/c81af6a/actionpack/lib/action_dispatch/middleware/remote_ip.rb#L112-L150 | |
Rails.application.configure do | |
ip_ranges_res = Faraday.get('https://ip-ranges.amazonaws.com/ip-ranges.json') | |
ip_ranges = JSON.parse(ip_ranges_res.body) | |
cloudfront_ips = ip_ranges['prefixes'].select { |v| v['service'] == 'CLOUDFRONT' }.map { |v| IPAddr.new(v['ip_prefix']) } + | |
ip_ranges['ipv6_prefixes'].select { |v| v['service'] == 'CLOUDFRONT' }.map { |v| IPAddr.new(v['ipv6_prefix']) } | |
config.action_dispatch.trusted_proxies = cloudfront_ips | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment