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

Spring Security 6按请求匹配器配置AuthenticationProvider方案问询

解决方案:使用多实例SecurityFilterChain实现路径拆分认证

在Spring Security 6中,由于and()方法弃用且单HttpSecurity实例无法重复指定authenticationManager,正确的做法是创建多个SecurityFilterChain Bean,通过@Order控制优先级,每个链独立负责对应路径的认证与授权规则。

步骤1:配置Basic认证专用FilterChain

这个链优先匹配/basic-path/**路径,仅启用HTTP Basic认证并绑定对应的basicAuthManager:

@Bean
@Order(1)
fun basicSecurityFilterChain(http: HttpSecurity, basicAuthManager: AuthenticationManager): SecurityFilterChain {
    return http
        .securityMatcher("/basic-path/**") // 仅对该路径生效
        .authorizeHttpRequests { auth ->
            auth.anyRequest().hasAnyAuthority("ROLE_BASIC")
        }
        .authenticationManager(basicAuthManager)
        .httpBasic {} // 仅启用Basic认证
        .build()
}

步骤2:配置SAML认证专用FilterChain

这个链匹配/other-path/**路径,启用SAML2登录并绑定samlAuthManager:

@Bean
@Order(2)
fun samlSecurityFilterChain(http: HttpSecurity, samlAuthManager: AuthenticationManager): SecurityFilterChain {
    return http
        .securityMatcher("/other-path/**") // 仅对该路径生效
        .authorizeHttpRequests { auth ->
            auth.anyRequest().hasAnyAuthority("ROLE_SAML")
        }
        .authenticationManager(samlAuthManager)
        .saml2Login { saml ->
            saml.authenticationManager(samlAuthManager)
            // 其他SAML配置(如断言处理器、身份提供者配置等)
        }
        .build()
}

步骤3:(可选)默认路径处理FilterChain

如果有其他未匹配的路径,可以添加一个默认FilterChain(优先级最低),根据需求配置访问规则:

@Bean
@Order(3)
fun defaultSecurityFilterChain(http: HttpSecurity): SecurityFilterChain {
    return http
        .authorizeHttpRequests { auth ->
            auth.anyRequest().denyAll() // 或其他规则,比如允许匿名等
        }
        .build()
}

关键说明

  • securityMatcher():指定当前FilterChain生效的路径范围,避免全局生效
  • @Order:数值越小优先级越高,确保先匹配更具体的路径规则
  • 每个FilterChain独立配置认证方式(Basic/SAML)和对应的authenticationManager,互不干扰,完全实现按路径拆分认证提供者的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:53:22