[ruby on rails]rack-cors, rack-attack

ruby 复制代码
gem 'rack-attack'
gem 'rack-cors'

1. rack-attack 可以根据ip、域名等设置黑名单、设置访问频率

  • 设置黑名单
ruby 复制代码
# 新增 config/initializers/rack_attack.rb
# 请求referer如果匹配不上设置的allowed_origins,返回403 forbidden
Rack::Attack.blocklist('block bad domains') do |req|
  next if !req.path.start_with?('/admin_api/') || Rails.env.test?

  Rails.application.credentials.allowed_origins.none? { |r| Regexp.new(r) =~ req.referer }
end

# EDITOR="vim" bin/rails credentials:edit
allowed_origins:
  - api.xxx.net
  - localhost
  • 设置访问频率
ruby 复制代码
class Rack::Attack
  # Rack::Attack.cache.store = ActiveSupport::Cache::RedisCacheStore.new(url: "...")
  Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
  # key: "rack::attack:#{Time.now.to_i/:period}:public_data/ip:#{req.ip}"
  throttle('public_data/ip', limit: 2, period: 1.minutes) do |req|
    req.ip if req.path.start_with?('/pc/v1/public_data')
  end

  self.throttled_responder = lambda do |_env|
    [429, # status
     {}, # headers
     ['throttling, retry later']] # body
  end
end

2. rack-cors 可以根据域名、访问方法、资源设置跨域请求cors

ruby 复制代码
# config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head],
  end
end
  • 复杂一些
ruby 复制代码
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost:3000', '127.0.0.1:3000',
            /\Ahttp:\/\/192\.168\.0\.\d{1,3}(:\d+)?\z/
            # regular expressions can be used here

    resource '/file/list_all/', :headers => 'x-domain-token'
    resource '/file/at/*',
        methods: [:get, :post, :delete, :put, :patch, :options, :head],
        headers: 'x-domain-token',
        expose: ['Some-Custom-Response-Header'],
        max_age: 600
        # headers to expose
  end

  allow do
    origins '*'
    resource '/public/*', headers: :any, methods: :get

    # Only allow a request for a specific host
    resource '/api/v1/*',
        headers: :any,
        methods: :get,
        if: proc { |env| env['HTTP_HOST'] == 'api.example.com' }
  end
end
相关推荐
捂月43 分钟前
Spring Boot 深度解析:快速构建高效、现代化的 Web 应用程序
前端·spring boot·后端
瓜牛_gn1 小时前
依赖注入注解
java·后端·spring
Estar.Lee1 小时前
时间操作[取当前北京时间]免费API接口教程
android·网络·后端·网络协议·tcp/ip
喜欢猪猪1 小时前
Django:从入门到精通
后端·python·django
一个小坑货1 小时前
Cargo Rust 的包管理器
开发语言·后端·rust
bluebonnet272 小时前
【Rust练习】22.HashMap
开发语言·后端·rust
uhakadotcom2 小时前
如何实现一个基于CLI终端的AI 聊天机器人?
后端
Iced_Sheep2 小时前
干掉 if else 之策略模式
后端·设计模式
XINGTECODE3 小时前
海盗王集成网关和商城服务端功能golang版
开发语言·后端·golang
程序猿进阶3 小时前
堆外内存泄露排查经历
java·jvm·后端·面试·性能优化·oom·内存泄露