9

I'm using Spring Cloud's Zuul to proxy some API requests to a few external servers. The proxying itself works well, but each service requires a (different) token provided in the request header.

I've successfully written a simple pre filter for each token that applies the appropriate header. However, I now have a problem. Even after pouring through the documentation, I can't figure out how to make each filter apply only to the proper route. I don't want to perform url-matching as the url changes across environments. Ideally, I'd have some way to get the name of the route in the filter.

My application.yml:

zuul:
  routes:
    foo:
      path: /foo/**
      url: https://fooserver.com
    bar:
      path: /bar/**
      url: https://barserver.com

Ideally I'd like to do something like this in FooFilter.java (a prefilter):

public bool shouldFilter() {
    return RequestContext.getCurrentContext().getRouteName().equals("foo");
}

but I can't seem to find any way to do this.

Xcelled
  • 2,084
  • 3
  • 22
  • 40

1 Answers1

24

You can use proxy header in RequestContext to distinguish routed server like below. If you are using ribbon, you can also use serviceId header. But if you specify url direclty like above your example, you should use proxy header. One thing you have to know is that proxy header is set in PreDecorationFilter, so your pre-filter must have bigger value of filter order than the value that PreDecorationFilter has (it is 5 at this moment).

@Override
public int filterOrder() {
    return 10;
}

@Override
public boolean shouldFilter() {
    RequestContext ctx = RequestContext.getCurrentContext();

    if ((ctx.get("proxy") != null) && ctx.get("proxy").equals("foo")) {
        return true;
    }
    return false;
}
yongsung.yoon
  • 5,489
  • 28
  • 32
  • 3
    Wow I can't believe how hard this was to find! Thanks! – Xcelled Apr 10 '17 at 13:07
  • 5
    Minor comment: if could be simplified with "foo".equals( ctx.get( "proxy" ) – Martin Dürrmeier Nov 13 '17 at 13:06
  • Where can I find the details about the order number given in filter? – balaaagi Jan 02 '18 at 16:14
  • 1
    @BalajiSrinivasan You can find the order here - FileConstants.java https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java#L78 – yongsung.yoon Jan 04 '18 at 02:46
  • 1
    I am using Spring Boot 2.2.6.RELEASE and unfortunately it does not work, there is no "proxy" object associated with RequestContext. Any other idea? – Istvan Kiss Jun 17 '20 at 15:27
  • I'm using Spring Boot 2.3.0. and it contains the "proxy" object. Just FYI. – mazend Oct 19 '21 at 08:28