根据 IP 地址限制对 Rails 应用程序的访问

Restricting Access to Rails App based on IP-Address

我想制作一个只能通过特定网络连接访问的应用程序。更明确地说,它将是一个考勤应用程序。用户只能从特定的网络连接签入。如果他们连接到其他网络,则无法签入。 我怎样才能在 Rails 上的 Ruby 中做到这一点?请给我一些想法。其实我需要知道如何检测特定的网络连接?

提前致谢。

在您的 ApplicationController 中添加:

before_filter :block_foreign_hosts

def whitelisted?(ip)
  return true if [123.43.65.1, 123.43.65.77].include?(ip)
  false
end

def block_foreign_hosts
  return false if whitelisted?(request.remote_ip)
  redirect_to "https://www.google.com" unless request.remote_ip.start_with?("123.456.789")
end

当然,您必须将我在此示例中使用的 IP 网络替换为您想要访问的 IP 网络。