Rails API - Throttling with Rack::Attack

#52 Rails API - Throttling with Rack::Attack
10/30/2016

Summary

Save expensive calculation time using Rack::Attack, we will learn how to limit requests coming into our application. This gem not only limits requests, but can be used to blacklist or whitelist users as well.
0
rails api security

Summary

Gemfilegem 'rack-attack'
config/application.rbmodule Template
  class Application < Rails::Application
    ...
    config.middleware.use Rack::Attack
  end
end
config/initializers/rack_attack.rbclass Rack::Attack
  Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new 

  throttle('api/ip', limit: 3, period: 10) do |req|
    req.ip if req.subdomain == 'api'
  end

  class Request < ::Rack::Request
    def subdomain
      host.split('.').first
    end
  end
end
142157?v=3&s=64
dancinglightning said 7 days ago:

Very nice. I use it on every app nowadays. Throtteling off course, but also to deal with probes:

Rack::Attack.blacklist('block admin probes') do |req|

  # Request are blocked if the return value is truthy

  block = false

  ["php" , "jsp" , "cgi", "asp", "cfm," "proxy.txt", "soapCaller", "Win32" , "HNAP1" , "w00tw00t",

    "pma" , "mysql" ,"msd" , "MySQL" , "jmx-console" , "ervlet" , "xml" , "cart" ,"install"].each do |no|

    block = true if  req.path.include?(no)

  end

  block

end

 

Login to Comment