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

Spring Security 5迁移至6:requestMatchers方法缺失求助

Spring Security 迁移:requestMatchers() 方法不存在的解决方案

在从WebSecurityConfigurerAdapter迁移到SecurityFilterChain Bean的过程中,你遇到的requestMatchers()方法不存在问题,是因为Spring Security 6+对HttpSecurity的API做了调整,原有的方法被移除或替换了。以下是适配新版本的正确配置代码及关键说明:

正确迁移后的配置

@Configuration
@EnableWebSecurity
class OpenApiSecurityConfig {

    @Bean
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http
            // 指定当前FilterChain仅处理匹配/docs路径的请求
            .securityMatcher("/docs")
            // 将自定义过滤器添加到AuthorizationFilter之前
            .addFilterBefore(MyApiFilter(), AuthorizationFilter::class.java)
            // 根据实际需求配置授权规则(示例为允许所有请求)
            .authorizeHttpRequests { auth ->
                auth.anyRequest().permitAll()
            }

        return http.build()
    }
}

关键变化说明

  • 请求匹配方式变更:原代码中http.requestMatchers().antMatchers("/docs")的作用是限定过滤器仅作用于指定路径,新版本中用securityMatcher("/docs")实现相同效果,该方法会指定当前SecurityFilterChain的作用范围。如果需要匹配多个路径,可以传入多个参数,比如securityMatcher("/docs", "/docs/**")。
  • 必须调用build():原示例迁移代码缺少http.build()调用,这会导致无法生成SecurityFilterChain实例,编译报错,必须补充这一步。
  • 过滤器位置调整:原代码使用FilterSecurityInterceptor::class.java作为过滤器前置位置,新版本中该类已被AuthorizationFilter替代,所以替换为AuthorizationFilter::class.java是正确的。

内容的提问来源于stack exchange,提问作者Vojtěch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:10:45