Spring Boot拦截器未触发TRACE请求,求排查解决
Spring Boot拦截器不触发TRACE请求的解决办法
问题根源
如果你的项目引入了Spring Security,它默认会直接拦截所有TRACE请求——这类请求在到达你的自定义拦截器之前就被处理返回了,所以BlockingHttpInterceptor完全没机会执行。
解决步骤
1. 配置Spring Security放行TRACE请求(如果项目使用了Security)
如果项目依赖了spring-boot-starter-security,需要显式配置允许TRACE方法:
Spring Boot 2.x版本(基于WebSecurityConfigurerAdapter)
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests().anyRequest().permitAll() .and().csrf().disable() // 放行所有路径的TRACE请求 .authorizeRequests() .antMatchers(HttpMethod.TRACE, "/**").permitAll(); } }
Spring Boot 3.x版本(基于SecurityFilterChain)
@Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) .csrf(csrf -> csrf.disable()) // 允许TRACE请求 .requestMatchers(req -> HttpMethod.TRACE.name().equals(req.getMethod())) .permitAll(); return http.build(); } }
2. 修改拦截器代码,处理TRACE请求
即使放行TRACE请求到达拦截器,当前代码会将其判定为非法方法返回405,需要把TRACE加入允许的方法列表:
更新BlockingHttpInterceptor的preHandle方法:
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String method = request.getMethod(); if (HttpMethod.GET.matches(method) || HttpMethod.POST.matches(method) || (HttpMethod.DELETE.matches(method) && request.getRequestURI().startsWith(BASE_URL)) || HttpMethod.PATCH.matches(method) || HttpMethod.TRACE.matches(method)) { // 新增TRACE方法的判断 return true; } else { response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value()); return false; } }
3. 未使用Spring Security的情况
如果项目没引入Security依赖,但TRACE请求仍无法触发拦截器,需要检查是否有自定义过滤器提前拦截了TRACE请求,或者确认Spring MVC是否有特殊配置限制。正常情况下,无Security时Spring MVC会允许TRACE请求到达拦截器。
内容的提问来源于stack exchange,提问作者YoramEi
相关产品推荐
相关产品推荐

