【问题标题】:Rails: possible to restrict a route based on IP address (or range?)Rails:可以根据 IP 地址(或范围?)限制路由
【发布时间】:2013-02-07 18:59:38
【问题描述】:

我知道这通常发生在控制器中,但我想知道 config/routes.rb 是否可以根据特定 IP(或 IP 范围)限制路由?有点像白名单。

例如,我想将此路由限制为仅限我们子网上的 IP:

#config/routes.rb
require 'sidekiq/web'

MyApp::Application.routes.draw do
  resources :users
  ...
  mount Sidekiq::Web, at: "/sidekiq"      # <== restrict this based on IP address
  ...
end

【问题讨论】:

  • 快速而肮脏的解决方案是在 ApplicationController 上添加 before_filter...

标签: ruby-on-rails routing routes sidekiq


【解决方案1】:

根据Rails Docs 中的示例,您可以这样做:

#config/routes.rb
require 'sidekiq/web'

MyApp::Application.routes.draw do
  resources :users
  ...
  mount Sidekiq::Web, at: "/sidekiq", :constraint => Whitelist.new
  ...
end

class Whitelist
  def initialize
    @ips = Whitelist.retrieve_ips
  end

  def matches?(request)
    @ips.include?(request.remote_ip)
  end

  def retrieve_ips
    # get and return your whitelist of ips
  end
end

This post by Yehuda Katz 更详细地介绍了约束以及如何使用它们。

【讨论】:

  • @ips = Whitelist.retrieve_ips 所以retrieve_ips 是一个类方法,所以def retrieve_ips 应该是def self.retrieve_ips
猜你喜欢
  • 2017-02-20
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 2022-07-22
  • 1970-01-01
相关资源
最近更新 更多