Search code examples
spring-bootnetflix-zuul

Spring boot Block country in zuul


I developed some services based on microservice pattern with api gateway, I using zuul for api gateway, I want to block some countries in gateway, I cannot implement it in network layer because i need to error page and status code


Solution

  • Countries are not in the HTTP Header. You will have to do a mapping between the IP and the country. Note also that the remote address of the client may be conveyed from multiple ways (direct and proxied mainly).

    So you can create a Zuul filter for :

    @Component
    public class CountryZuulFilter extends ZuulFilter {
    
        @Override
        public Object run() {
    
            RequestContext ctx = RequestContext.getCurrentContext();
            String ip = ctx.getRequest()
                           .getHeader("Remote_Addr");
            if (ip == null) {
                ip = ctx.getRequest().getHeader("HTTP_X_FORWARDED_FOR");
    
                if (ip == null) {
                    ip = ctx.getRequest().getRemoteAddr();
                }
    
            }
            // use an API to map the IP to a country
             String countryCode = lookupCountry(ip);
            // return a 401 if not authorized
            if (forbidenCountries.contains(countryCode)) {
                ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
            }
            return null;
        }
    
        @Override
        public boolean shouldFilter() {
           return true;
       }
    
       @Override
       public String filterType() {
          return "pre";
       }
    
       @Override
       public int filterOrder() {
           return 0;
       }
    
    }
    

    For retrieving the remote IP, credit to this answer.