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
相关产品推荐
相关产品推荐

