Spring Cloud Gateway MVC: unpredictable order of operation of custom filters

179 Views Asked by At

I am using Java21, Spring Boot 3.2 and spring-cloud-starter-gateway-mvc:4.1.1;

I am trying to port the gateway (webflux) to gateway-mvc and in the gateway I need to call the authorization service, then add the received data to the headers. I have a logging-starter used by all microservices, and it includes a class responsible for logging (RequestResponseFilter extends AbstractRequestLoggingFilter). I make the call to the authorization service in RouterFunction using .before(request -> {//call auth}), but I encountered a problem where RequestResponseFilter is invoked earlier, and the headers obtained from authorization do not appear in my log.

To achieve my goal, I tried using .filter() and .after() and noticed an unpredictable order of filter operations, depending on the coding style I use. For more clarity, I am attaching screenshots.

How can I better perform header enrichment in the gateway after contacting auth, so that by the time RequestResponseFilter is called, all the headers I need are already in the context?

@Slf4j
public class RequestResponseFilter extends AbstractRequestLoggingFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        log.info("AbstractRequestLoggingFilter Number");
        try {
            super.doFilterInternal(request, response, filterChain);
        } finally {
            MDC.clear();
        }
    }

}

enter image description here enter image description here

1

There are 1 best solutions below

2
On

I guess your "RequestResponseFilter" is a servlet filter. As all pre-actions taken by servlet filters are happening before any Spring Cloud Gateway MVC filters, the behaviour you observe is quite obvious.

I suggest to make the call to the authorization service in a custom servlet filter instead of Spring Cloud Gateway MVC filter.

Next, you can define ordering of servlet filter executions using @Order annotation. That way your custom servlet filter for authorization will be executing pre-actions before a pre-action of this "RequestResponseFilter".