[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
相关推荐
isolusion2 小时前
Springboot的创建方式
java·spring boot·后端
zjw_rp2 小时前
Spring-AOP
java·后端·spring·spring-aop
TodoCoder3 小时前
【编程思想】CopyOnWrite是如何解决高并发场景中的读写瓶颈?
java·后端·面试
凌虚3 小时前
Kubernetes APF(API 优先级和公平调度)简介
后端·程序员·kubernetes
机器之心4 小时前
图学习新突破:一个统一框架连接空域和频域
人工智能·后端
.生产的驴5 小时前
SpringBoot 对接第三方登录 手机号登录 手机号验证 微信小程序登录 结合Redis SaToken
java·spring boot·redis·后端·缓存·微信小程序·maven
顽疲5 小时前
springboot vue 会员收银系统 含源码 开发流程
vue.js·spring boot·后端
机器之心5 小时前
AAAI 2025|时间序列演进也是种扩散过程?基于移动自回归的时序扩散预测模型
人工智能·后端
hanglove_lucky6 小时前
本地摄像头视频流在html中打开
前端·后端·html
皓木.8 小时前
(自用)配置文件优先级、SpringBoot原理、Maven私服
java·spring boot·后端