You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security:替换已废弃的.shouldFilterAllDispatcherTypes(false)方法

解决方案

原来的shouldFilterAllDispatcherTypes(false)作用是关闭对所有DispatcherType的强制过滤,默认只处理DispatcherType.REQUEST。要替换这个废弃方法,同时适配StreamingResponseBody所需的ASYNC类型请求,你需要调整链式调用的结构——因为dispatcherTypeMatchers返回的是DispatcherType匹配器,之后需要先指定授权规则,或者使用支持同时指定DispatcherType和路径的requestMatchers重载方法。

方案1:使用requestMatchers同时指定DispatcherType和路径

直接通过requestMatchers的重载版本,把需要处理的DispatcherType和路径绑定在一起:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    // some code
    http.authorizeHttpRequests(customiser -> customiser
            // 指定要处理的DispatcherType和路径
            .requestMatchers(DispatcherType.REQUEST, DispatcherType.ASYNC, "/**")
            .authenticated());
    // some code
    return http.build();
}

方案2:拆分DispatcherType匹配和路径匹配

如果需要更灵活的规则拆分,可以先指定DispatcherType范围,再对路径应用授权:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    // some code
    http.authorizeHttpRequests(customiser -> customiser
            // 先匹配需要处理的DispatcherType
            .dispatcherTypeMatchers(DispatcherType.REQUEST, DispatcherType.ASYNC)
            .authenticated()
            // 确保其他请求也被处理(如果需要)
            .anyRequest()
            .authenticated());
    // some code
    return http.build();
}

关键说明

  • 如果你只想保留原代码的行为(仅处理REQUEST),只需要把DispatcherType.ASYNC去掉即可。
  • StreamingResponseBody会触发ASYNC类型的请求,所以必须将其加入到需要处理的DispatcherType列表中,否则异步请求会绕过安全过滤或者被拒绝。

内容的提问来源于stack exchange,提问作者ODDminus1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 03:20:09