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.rbconfig.whitelisted_ips = ['184.108.40.206', '220.127.116.11']
Now, we can use whitelisted_ips to define a constraint to restrict access to any other IP addresses than in the list.
# In lib/constraint/ip_authenticator.rbmodule Constraintclass IPAuthenticatordef matches?(request)Rails.application.config.whitelisted_ips.include?(request.remote_ip)endendend
# In config/routes.rbRails.application.routes.draw do# constraints on a resourceconstraints Constraint::IPAuthenticator.new doresources :usersend# constraints on a routeget \"list_user\", to: \"user#index\",constraints Constraint::IPAuthenticator.newend
If the remote_ip address of the request object matches the constraints, only then 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
Akshay is a Ruby on Rails and ReactJS enthusiast. He likes to write blog posts. Contributes to open source whenever gets some free time.