Search code examples
spring-bootnetflix-zuulspring-cloud-netflix

After enabling Zuul proxy for the Spring boot app (We have set of miroservices), spring mvc interceptor doesnot work


Below is the Application.java. It has code to invoke the interceptor

@EnableEurekaClient
@SpringBootApplication
@EnableZuulProxy
public class Application extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public TokenValidateInterceptor tokenValidateInterceptor() {
        TokenValidateInterceptor localeChangeInterceptor = new TokenValidateInterceptor();
        System.out.println("In WEB MVC Intereptor, Interceptor returned");
        return localeChangeInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("In WEB MVC Intereptor");
        // registry.addInterceptor(tokenValidateInterceptor()).addPathPatterns("/");
        registry.addInterceptor(tokenValidateInterceptor()).addPathPatterns("/api/**");
        // registry.addInterceptor(new
        // TokenValidateInterceptor()).addPathPatterns("/api/**");
    }

}

Below is the snippet of the interceptor code:

@Component
public class TokenValidateInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOG = Logger.getLogger(TokenValidateInterceptor.class);

    // before the actual handler will be executed ..
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String apikey = request.getHeader("apikey");
        // if (LOG.isDebugEnabled()) {
        LOG.info("#### Starting TokenValidateInterceptor.preHandle ####");
        LOG.info("apikey-->" + apikey);
        // }
        if (StringUtils.isBlank(apikey) || apikey == null || apikey.isEmpty()) {
                return true;
        }
}
}

But the call does not reach prehandle of the interceptor.


Solution

  • AFAIK, all requests that are defined in Zuul routing are handled by ZuulServlet. Spring MVC doesn't handle these requests, so any Spring HandlerInterceptor will not be called for these requests. If you need any preprocessing for API requests, you should implement it in Zuul prefilter or servlet filter.