0

我正在阅读有关 Rack::Throttle 的信息,我想将默认客户端标识符从 IP 更改为其他内容。文档说可以做到

由 Rack::Throttle 存储和维护的限速计数器被锁定到唯一的 HTTP 客户端。

默认情况下,HTTP 客户端由 Rack::Request#ip 返回的 IP 地址唯一标识。如果您希望改用更精细的、特定于应用程序的标识符(例如会话密钥或用户帐户名),则只需子类化一个限制策略实现并覆盖 #client_identifier 方法。

我不知道在哪里添加它,这是我当前的另一个方法的子类。有人知道怎么做这个吗?https://github.com/datagraph/rack-throttle

    module Rack
  module Throttle
    class DailyRequests < Daily
      def allowed?(request)
        ## Insert rules
        super request
      end
    end

    class HourlyRequests < Hourly
      def allowed?(request)
        ## Insert rules
        super request
      end
    end

    class RequestInterval < Interval
      def allowed?(request)
        ## Insert rules
        super request
      end
    end
  end
end
4

1 回答 1

1

You should subclass one of the existing rack-throttle classes (probably either Rack::Throttle::Interval or Rack::Throttle::TimeWindow, whichever one more closely aligns with your needs) and override the #client_identifier method.

#client_identifier is passed one argument, request, which is a Rack::Request instance containing information passed in the incoming HTTP request and can be used to get information such as HTTP headers, cookies, path, and possibly other info depending on your app. The default implementation looks like this:

# @param  [Rack::Request] request
# @return [String]
def client_identifier(request)
  request.ip.to_s
end

Here's an example of subclassing Rack::Throttle::Interval to match requests on a query parameter such as ?user_id=<id>:

class UserThrottle < Rack::Throttle::Interval
  def client_identifier(request)
    request['user_id']
  end
end

which you could use in a Rack application with:

use UserThrottle, :min => 100

Notice you can still pass options like :min to the Rack use statement, since it is just subclassing the existing throttle classes. And adopting this in a Rails app would just involve calling use in your application.rb file (see Rails on Rack).

于 2013-03-05T07:19:29.617 回答