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

Spring Security配置问题:排除/actuator/health仍需登录

问题分析与解决建议

核心问题

你的配置存在两个关键错误:

  1. 端点路径匹配错误:Actuator的health端点默认暴露路径是/actuator/health,而非你配置的/health,导致antMatchers("/health").permitAll()无法匹配实际请求路径。
  2. SecurityFilterChain作用范围限制:原配置中requestMatcher(EndpointRequest.toAnyEndpoint().excluding("health"))会让当前过滤器链只作用于除health外的Actuator端点,而/actuator/health可能被Spring Security的默认过滤器链拦截,触发认证校验。

修正后的配置方案

方案一:基于EndpointRequest的精准配置(推荐)

直接通过EndpointRequest匹配Actuator端点,明确权限规则:

@Configuration(proxyBeanMethods = false)
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(auth -> auth
                        // 允许health端点无需认证
                        .requestMatchers(EndpointRequest.to("health")).permitAll()
                        // 其他所有Actuator端点需要认证
                        .requestMatchers(EndpointRequest.toAnyEndpoint()).authenticated()
                )
                .httpBasic(); // 启用HTTP Basic认证
        return http.build();
    }
}

方案二:基于路径的直接匹配

如果更倾向于通过URL路径控制,可直接匹配Actuator的暴露路径:

@Configuration(proxyBeanMethods = false)
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(auth -> auth
                        // 允许/actuator/health无需认证
                        .antMatchers("/actuator/health").permitAll()
                        // 其他/actuator/**路径需要认证
                        .antMatchers("/actuator/**").authenticated()
                        // 非Actuator路径如果不需要保护,可添加此规则(根据实际需求调整)
                        .anyRequest().permitAll()
                )
                .httpBasic();
        return http.build();
    }
}

关于management配置的说明

你提供的management配置仅用于控制端点的细节展示和暴露范围,不会影响Spring Security的认证规则,无需调整这部分内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:42:38