Spring Boot 3.1.2返回响应式类型时Security过滤器链被调用两次问题
Spring Boot 3.1.2中MVC控制器返回响应式类型时Security过滤器链被调用两次的问题
当Spring Boot 3.1.2的Web MVC控制器返回响应式类型(如Mono<T>)时,Security过滤器链会被调用两次——一次在API方法执行前,一次在执行后。返回非响应式类型时则不会出现此问题。
最小复现示例
- 使用Spring Initializr创建包含web、webflux和security依赖的Spring Boot 3.1.2项目。
- 添加仅输出日志的自定义过滤器:
public class CustomFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { logger.info("Custom filter called"); chain.doFilter(request, response); } }
- 添加Security过滤器链Bean以引入该过滤器:
@Configuration public class CustomWebSecurityConfigurerAdapter { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); return http.build(); } }
- 添加用于测试的REST API:
@RestController public class RestApi { @GetMapping("/hello-reactive") Mono<String> helloReactive() { return Mono.just("hello world"); } @GetMapping("/hello") String hello() { return "hello world"; } }
测试结果
调用非响应式接口
$ curl localhost:8080/hello hello world
日志仅输出一次:
2023-08-11T10:30:02.232+01:00 INFO 24000 --- [nio-8080-exec-3] com.example.demo.CustomFilter : Custom filter called
调用响应式接口
$ curl localhost:8080/hello-reactive hello world
日志输出两次:
2023-08-11T10:32:12.776+01:00 INFO 24000 --- [nio-8080-exec-6] com.example.demo.CustomFilter : Custom filter called 2023-08-11T10:32:12.779+01:00 INFO 24000 --- [nio-8080-exec-6] com.example.demo.CustomFilter : Custom filter called
内容的提问来源于stack exchange,提问作者Andy Brown
相关产品推荐
相关产品推荐

