GlobalFilter vs WebFilter

Viewed 2304

I'm taking the first step in Spring Cloud Gateway. During the study, I wanted to understand better the use of GlobalFilter. In the specific, I intend to have some filter applied every time for every route.

Reading the documentation (reference) there are two ways for reaching my goal. The first is the use of GlobalFilter and the second is to have a GatewayFilter in default-filters.

Both the solutions work pretty well, but only for the routes defined in the YAML configuration. If I have any RouteLocator or RouterFunctions I need to declare the filter every time

.filters(f -> f.globalFilter("something"))

The only way that I have found for reaching my goal is to use directly a WebFilter (reference)

So my question here is if anybody can explain the difference between the two filters GatewayFilter/GlobalFilter and Webfilter

Maybe the answer is in the Spring documentation, but I can not find it.

Thank you in advance!

1 Answers

If you want to have a filter for every single route (for routes defined in the YAML as well as controllers / endpoints hosted in your gateway itself), WebFilter should be the way to go.

If you want a filter for all the routes, but not for the endpoints hosted in your gateway, then you can go for Default Filters / Global Filters.

And lastly, you have GatewayFilters that can be configured for specific routes.

I noticed in the source code that the routes go via FilteringWebHandler and the endpoints within the gateway are mapped directly to the controller methods and they don't really go via these handlers (they go via normal WebFilters though). Hence, the above.

Related