Restricting Access by IP Address
Learn to lock down your application or parts of your application by IP Addresses.
SummaryLearn to lock down your application or parts of your application by IP Addresses.
Additional Notes: Depending on the complexity and requirements of your application, you can also use advanced routing with constraints to achieve the same thing.
class ApplicationController < ActionController::Base protect_from_forgery with: :exception # before_action :verify_ip_address private def verify_ip_address head :unauthorized if Whitelist.find_by(ip_address: request.remote_ip).nil? # if Whitelist.find_by(ip_address: request.remote_ip).nil? # redirect_to root_path, alert: 'Unauthorized access.' # end end end
You may want to limit the size of the IP Address column to 16 characters or 45 for IPv6 support.
class CreateWhitelists < ActiveRecord::Migration[5.1] def change create_table :whitelists do |t| t.string :ip_address, limit: 16 # 45 Characters for IPv6 support t.timestamps end add_index :whitelists, :ip_address end end
class WelcomeController < ApplicationController # skip_before_action :verify_ip_address, only: :index before_action :verify_ip_address, only: :restricted def index end def restricted end end