Restricting Access by IP Address

Episode #92 by Teacher's Avatar David Kimura

Summary

Learn to lock down your application or parts of your application by IP Addresses.
rails security 4:22

Resources

Additional Notes: Depending on the complexity and requirements of your application, you can also use advanced routing with constraints to achieve the same thing.

Summary

# application_controller.rb
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.

# whitelist_migration.rb
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

# welcome_controller.rb
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