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.
There are four types of standard filters in Zuul: pre for pre-routing filtering, route for routing to an origin, post for post-routing filters, and error for error handling. Zuul also supports a static type for static responses. Any filter type can be created or added and run by calling the method runFilters(type).
The default HTTP client used by Zuul is now backed by the Apache HTTP Client instead of the deprecated Ribbon RestClient .
To enable it, annotate a Spring Boot main class with @EnableZuulProxy . Doing so causes local calls to be forwarded to the appropriate service. By convention, a service with an ID of users receives requests from the proxy located at /users (with the prefix stripped).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With