开发者

With Rails 3 routes, how do you only allow a requests from 127.0.0.1?

开发者 https://www.devze.com 2023-01-03 09:36 出处:网络
I\'m writing an app where several of the routes should only be accessible from localhost. It looks like this is possible with the new routing system.

I'm writing an app where several of the routes should only be accessible from localhost. It looks like this is possible with the new routing system.

http://www.railsdispatch.com/posts/rails-3-makes-life-better

This has examples of restricting routes based on IP address, and setting up an IP address blacklist for your routes, but I'm interested in a whitelist with just one IP address.

It would be cool if something like this worked:

get "/posts" =开发者_JAVA百科> "posts#show", :constraints => {:ip => '127.0.0.1'}

But it didn't. Am I just missing the right syntax?


you can do this

get "/posts" => "posts#show", :constraints => {:ip => /127.0.0.1/}

or this

constraints(:ip => /127.0.0.1/) do
  get "/posts" => "posts#show"
end


following the example in Yehuda's post, you shoud create an approriate object to handle complex constraints. so, just editing that example could help. there's a line of code which checks if some ip is blacklisted:

!@ips.include?(request.remote_ip)

you should write similar logic (but simpler) that checks if request.remote_ip == 127.0.0.1

0

精彩评论

暂无评论...
验证码 换一张
取 消