Sometimes we need to limit access based on IP address and whitelist only certain IP addresses to access a route. We can use rails routing constraints to restrict an access. We can either whitelist or blacklist IP addresses for a route.
Rails provides different basic constraints on routes like:
Let’s say, we have a list of IP addresses to whitelist. We can configure such IP address in Rails configuration as given below.
# In config/environments/development.rb config.whitelisted_ips = ['188.8.131.52', '184.108.40.206']
Now, we can use
whitelisted_ips to define a constraint to restrict access to any other IP addresses than in the list.
- Define a constraint
# In lib/constraint/ip_authenticator.rb module Constraint class IPAuthenticator def matches?(request) Rails.application.config.whitelisted_ips.include?(request.remote_ip) end end end
- Apply the constraint to a route
# In config/routes.rb Rails.application.routes.draw do # constraints on a resource constraints Constraint::IPAuthenticator.new do resources :users end # constraints on a route get "list_user", to: "user#index", constraints Constraint::IPAuthenticator.new end
remote_ip address of the request object matches the constraints we then only the request is served otherwise rails responds the request with
ActionController::RoutingError (No route matches)
Apart from the basic routing constraints, one can add some advanced constraints on route/routes. Restricting the access to a route based on the IP address is also possible