【问题标题】:How to make Rack::Attack work behind a load balancer?如何让 Rack::Attack 在负载均衡器后面工作?
【发布时间】:2015-11-04 22:40:02
【问题描述】:

我使用 Rack::Attack 的示例节流代码。

throttle('req/ip', limit: 100, period: 5.minutes) do |req|
  req.ip unless req.path.starts_with?('/assets')
end

这在我们的暂存服务器上运行良好,但立即遇到了生产限制,因为 req.ip 返回的是负载均衡器的 IP 地址,而不是客户端的 remote_ip。

请注意,remote_ip 是 ActionDispatch::Request 中的方法,而不是 Rack::Attack::Request 中的方法。

我们在 Ruby 2.2 上使用 Rails 3.2.2。

【问题讨论】:

    标签: ruby-on-rails rackattack


    【解决方案1】:

    我能够通过向 Rack::Attack::Request 添加一个方法来使其工作

    class Rack::Attack
      class Request < ::Rack::Request
        def remote_ip
          @remote_ip ||= (env['action_dispatch.remote_ip'] || ip).to_s
        end
      end
    end
    

    然后使用

    req.remote_ip unless req.path.starts_with?('/assets')
    

    【讨论】:

    • 为什么不将路径 /assets 列入白名单?
    • 这解决了 /assets 特定情况的问题,但不能解决每个请求具有相同客户端 IP 地址的更普遍问题。
    猜你喜欢
    • 2011-09-22
    • 2021-05-25
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2021-03-16
    • 1970-01-01
    相关资源
    最近更新 更多