如何将actuator从SecurityWebFilterChain授权中排除?代码无效求助
问题原因及解决方案
一、多SecurityWebFilterChain的匹配逻辑错误(你的第一段代码)
你创建的两个SecurityWebFilterChain Bean存在规则冲突:
- 第一个标注
@Order(Ordered.HIGHEST_PRECEDENCE)的Bean,使用NegatedServerWebExchangeMatcher仅对**非/actuator/health**的请求生效,要求这些请求必须认证。 - 第二个
springSecurityFilterChain没有指定securityMatcher,会匹配所有请求(包括/actuator/health),而它的anyExchange().authenticated()规则会强制要求认证,直接覆盖了第一个Bean的排除逻辑。
修复方案
调整第一个Bean的匹配逻辑,让它仅处理actuator路径并直接放行:
@Order(Ordered.HIGHEST_PRECEDENCE) @Bean public SecurityWebFilterChain actuatorSecurityFilterChain(ServerHttpSecurity http) { return http .securityMatcher(ServerWebExchangeMatchers.pathMatchers("/actuator/**")) .authorizeExchange(exchanges -> exchanges .anyExchange().permitAll()) .csrf().disable() .build(); } @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.csrf().disable() .authorizeExchange(exchanges -> exchanges .pathMatchers("/domains/**", "/address/**").permitAll() .anyExchange().authenticated()) .httpBasic() .and() .formLogin().disable(); return http.build(); }
优先级最高的第一个FilterChain会先处理所有/actuator/**请求并放行,第二个FilterChain仅处理剩余请求,应用原有认证规则。
二、简化代码仍失效的可能原因(你的第二段代码)
如果单FilterChain配置pathMatchers("/actuator/**").permitAll()仍要求授权,大概率是以下情况:
- Actuator基础路径不匹配:如果你的配置文件(
application.yml/application.properties)中设置了management.endpoints.web.base-path(比如/manage),则路径匹配需改为pathMatchers("/manage/**").permitAll()。 - 缺少
securityMatcher限定范围:WebFlux环境下,部分Spring Security版本需要显式指定securityMatcher来锁定FilterChain的作用范围,否则可能存在规则冲突。可以补充配置:
@Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { return http .securityMatcher(ServerWebExchangeMatchers.pathMatchers("/**")) .authorizeExchange(exchanges -> exchanges .pathMatchers("/actuator/**", "/domains/**", "/address/**").permitAll() .anyExchange().authenticated()) .httpBasic() .and() .formLogin().disable() .csrf().disable(); }
- 存在其他Security配置类:检查项目中是否有其他
@Configuration类配置了Spring Security,可能会覆盖当前规则。
内容的提问来源于stack exchange,提问作者JackTheKnife
相关产品推荐
相关产品推荐

