0

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

Ali
  • 443
  • 5
  • 22

1 Answers1

1

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • It depends on the API that you use to map the IP to a country. You could still use a cache for the mapping. – davidxxx Mar 04 '19 at 16:22