当前位置: 首页 > news >正文

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

gem 'rack-attack'
gem 'rack-cors'

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

  • 设置黑名单
# 新增 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
  • 设置访问频率
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')endself.throttled_responder = lambda do |_env|[429, # status{}, # headers['throttling, retry later']] # bodyend
end

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

# config/initializers/cors.rbRails.application.config.middleware.insert_before 0, Rack::Cors doallow doorigins '*'resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head],end
end
  • 复杂一些
Rails.application.config.middleware.insert_before 0, Rack::Cors doallow doorigins 'localhost:3000', '127.0.0.1:3000',/\Ahttp:\/\/192\.168\.0\.\d{1,3}(:\d+)?\z/# regular expressions can be used hereresource '/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 exposeendallow doorigins '*'resource '/public/*', headers: :any, methods: :get# Only allow a request for a specific hostresource '/api/v1/*',headers: :any,methods: :get,if: proc { |env| env['HTTP_HOST'] == 'api.example.com' }end
end
http://www.lryc.cn/news/237698.html

相关文章:

  • 猫12分类:使用多线程爬取图片的Python程序
  • 《深度学习500问》外链笔记
  • 机器学习技术栈—— 概率学基础
  • 使用Redis实现分布式锁
  • linux 服务器进程、端口查找,nginx 配置日志查找,lsof 命令详解
  • 汽车标定技术--A2L格式分析
  • Linux操作系统使用及C高级编程-D9D10Linux 服务搭建与使用
  • git下载安装配置及Git在Gitee上拉取和上传代码教程
  • ospf路由选路及路由汇总
  • Oracle 11g 多数据库环境下的TDE设置
  • vue3使用pinia实现数据缓存
  • 【CSS】min 和 max 函数(设置最大最小值)
  • ip地址跟wifi有关系吗
  • [算法学习笔记](超全)概率与期望
  • SpringCloud相关
  • 在 Linux 和 Windows 系统下查看 CUDA 和 cuDNN 版本的方法,包括使用 nvcc 命令
  • 4.10每日一题(二元函数极值相关重要性质,反复学习)
  • idea项目中java类名出现带 j 小红点,如何解决?
  • 生产环境_移动目标轨迹压缩应用和算法处理-Douglas-Peucker轨迹压缩算法
  • HINSTANCE是什么?
  • uniapp小程序定位;解决调试可以,发布不行的问题
  • C++学习 --pair
  • Android Frgment中onActivityResult无效的问题
  • 【C#二开业务冠邑】通过界面查看数据来源
  • 使用大语言模型 LLM 做文本分析
  • Windows本地搭建rtmp推流服务
  • 机器学习二元分类 二元交叉熵 二元分类例子
  • Postgresql运维信息(一)
  • Jupyter Notebook的下载安装与使用教程_Python数据分析与可视化
  • 快速入门:构建您的第一个 .NET Aspire 应用程序