Rails 3 - 通过路由将 IP 列入白名单 [英] Rails 3 - Whitelisting list of IPs via routes
问题描述
这是一个两部分的问题.我需要将我在开发服务器上投放的 rails 站点限制为仅几个 IP 地址,因此公众无法访问它.(基本 HTTP 身份验证不能完全"工作,因为身份验证会破坏项目中的 Flash 上传器.)
This is a two part question. I'm needing to restrict a rails site that I'm throwing on development server to only a few IP addresses, so the public can't access it. (Basic HTTP auth doesn't 'entirely' work as the auth breaks a Flash uploader in the project.)
根据我在 Google 上搜索到的内容,这就是我在路由文件中提出的内容...
Based on what I've Googled, this is what I've come up with in my routes file...
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 上使用数组,以及遍历 each 循环,但都没有奏效.
Works pretty good. However, I need to modify this in order to work with several IP addresses. I tried using a array on @ips, as well as looping through an each loop, but neither worked.
最重要的是,我的问题的第二部分...我可能只需要检查 IP 的一部分,例如127.0.0".我该怎么做?
On top of that, the second part of my question...I may need to check only against a segment of the IP, like '127.0.0'. How would I do that?
推荐答案
我不知道你可以通过路由来做到这一点,我的方法是在 中有一个
并有一些功能:before_filter
ApplicationController
I didn't know you could do this through routes, my approach would be to just have a before_filter
in the ApplicationController
and just have something that does:
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
这篇关于Rails 3 - 通过路由将 IP 列入白名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!