Restricting Access by IP Address

#92 Restricting Access by IP Address
8/6/2017

Summary

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

Resources

Source - https://github.com/driftingruby/092-restricting-access-by-ip-address

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

http://guides.rubyonrails.org/routing.html#advanced-constraints

Summary

application_controller.rbclass 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.rbclass 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.rbclass WelcomeController < ApplicationController
  # skip_before_action :verify_ip_address, only: :index
  before_action :verify_ip_address, only: :restricted
  def index
  end

  def restricted
  end
end


310475?v=4&s=64
Kjarrigan said 3 months ago:

We use something similiar to disable login for api-calls from within our company network. Looks something like this:

skip_before_action :authenticate_user!
before_action :verify_user
ALLOWED_IP_ADDRESS_RANGES = %w(127.0.0.0/24)
  
def verify_user
  allowed = ALLOWED_IP_ADDRESS_RANGES.find do |addr|
    range = IPAddr.new(addr)
    range.include? IPAddr.new(request.ip)
  end
  unless allowed
    render plain: "Unauthorized", status: Foo::STATE_IP_NOT_IN_RANGE
  end
end

Login to Comment