Rails 3 - 通过路由将白名单IP列入清单
问题描述:
这是一个两部分问题。我需要将我在开发服务器上投放的rails网站限制为只有几个IP地址,因此公众无法访问它。 (基本的HTTP验证并不完全正常,因为验证会破坏项目中的Flash上传器。)Rails 3 - 通过路由将白名单IP列入清单
基于我谷歌搜索的内容,这是我在我的路由文件中提出的。 。
class WhitelistConstraint
def initialize
@ips = '127.0.0.1'
end
def matches?(request)
@ips.include?(request.remote_ip)
end
end
MyProject::Application.routes.draw do
constraints WhitelistConstraint.new do
# all my routing stuff here
end
end
工程很不错。但是,我需要修改这个以便使用多个IP地址。我尝试在@ips上使用数组,以及循环遍历每个循环,但都无效。
最重要的是,我的问题的第二部分...我可能只需要检查一段IP,如'127.0.0'。我会怎么做?
答
我不知道,你可以通过途径做到这一点,我的办法是只在一个ApplicationController
和before_filter
只是有东西做:关于使用NetAddr::CIDR
before_filter :protect
def protect
@ips = ['127.0.0.1', '203.123.10.1'] #And so on ...]
if not @ips.include? request.remote_ip
# Check for your subnet stuff here, for example
# if not request.remote_ip.include?('127.0,0')
render :text => "You are unauthorized"
return
end
end
答
什么?
和类似的东西?
class WhitelistConstraint
def initialize
@ips = []
@ips << NetAddr::CIDR.create('127.0.0.0/8')
@ips << NetAddr::CIDR.create('192.168.0.0/16')
end
def matches?(request)
valid = @ips.select {|cidr| cidr.contains?(request.remote_ip) }
!valid.empty?
end
end
MyProject::Application.routes.draw do
constraints WhitelistConstraint.new do
# all my routing stuff here
end
end
这样,您可以指定应列入白名单的IP块,而不必担心部分匹配?
>> require 'netaddr'
=> true
>> @ips = []
=> []
>> @ips << NetAddr::CIDR.create('127.0.0.0/8')
=> [127.0.0.08]
>> @ips << NetAddr::CIDR.create('192.168.0.0/16')
=> [127.0.0.08, 192.168.0.016]
>> @ips.select { |c| c.contains? '192.168.10.1' }
=> [192.168.0.016]
>> @ips.select { |c| c.contains? '192.169.10.1' }
=> []
答
或者干脆使用Apache的.htaccess:
- 添加以下到的http.conf或任何的conf文件,你有Apache和
的AllowOverride所有的Rails应用程序
- 创建文件的.htaccess在轨文件夹,并添加以下
Allow from xxx.xxx.xxx.xxx Deny from all
答
也可以包围,象这样一个范围路线声明:
scope :constraints => lambda{|req|%w(127.0.0.1).include? req.remote_addr} do
... your beautiful routes
end
我没你也知道你也可以。然而,这个解决方案对我来说很有效,可能是更好的路线。可以看到它是从开发到生产(暂时是临时服务器)的问题,但它只是暂时的,我可以根据需要在两个环境中添加IP。谢谢。 – Shannon 2011-04-05 15:45:26
你可以使用'Rails.env.production?'和'Rails.env.development?'来检查某种'if'结构中的环境,以适合你需要做的任何事情。祝你好运:) – 2011-04-05 15:49:45
这个解决方案适用于IP范围吗? – DanielCW 2012-08-29 16:18:17