Rails IP-Based access restriction with route constraints
November 19, 2019
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:
- HTTP Verb Constraints
- Segment Constraints
- Request-Based Constraints
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 = ['220.127.116.11', '18.104.22.168']
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 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