Spring Boot升级后健康检查链接重定向至登录页的解决求助
解决Spring Boot升级后健康检查链接被重定向至登录页的问题
我之前在升级Spring Boot版本时也碰到过一模一样的问题,大概率是版本升级后Spring Security或者Actuator的默认安全配置发生了变化,导致健康检查端点被拦截并重定向到登录页。下面是几个亲测有效的解决方案,按优先级从高到低来:
1. 调整Spring Security配置,允许健康端点匿名访问
这是最常见的原因——升级后Spring Security的默认拦截规则变严格了,把健康检查端点也纳入了需要认证的范围。你可以通过自定义Security配置类来放开这个端点:
针对Spring Security 6.x(对应Spring Boot 3.x+)的写法
import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth // 允许健康检查端点匿名访问 .requestMatchers("/actuator/health", "/actuator/health/**").permitAll() // 其他请求需要认证 .anyRequest().authenticated() ) // 如果你的项目用了表单登录,保留这部分配置 .formLogin(form -> form .loginPage("/login") .permitAll() ); return http.build(); } }
针对Spring Security 5.x(对应Spring Boot 2.x)的写法
如果是从2.x升级的,也可以用旧的链式写法:
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/actuator/health", "/actuator/health/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll(); } }
⚠️ 注意:如果自定义了Actuator的基础路径(比如配置了management.endpoints.web.base-path=/manage),记得把上面的端点路径改成/manage/health。
2. 检查并调整Actuator的配置
有时候Actuator本身的配置也会影响端点的访问权限,在application.properties或application.yml里添加以下配置,确保健康端点被正确暴露且允许匿名访问:
Properties格式
# 暴露健康检查端点(默认可能只暴露health) management.endpoints.web.exposure.include=health # 允许显示健康详情(可选,方便排查问题) management.endpoint.health.show-details=always # 清空健康端点需要的角色,允许匿名访问 management.endpoint.health.roles=
YAML格式
management: endpoints: web: exposure: include: health endpoint: health: show-details: always roles: ""
3. 排查自定义拦截器/过滤器
如果上面两种方法都没用,那就要检查项目里的自定义Filter或者拦截器了。版本升级后,这些组件的优先级或者拦截规则可能发生了变化,导致误拦截了健康检查请求。你需要确保这些自定义组件把/actuator/health(或你自定义的路径)加入到排除列表中。
比如自定义拦截器的配置:
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new YourCustomInterceptor()) .excludePathPatterns("/actuator/health", "/actuator/health/**"); } }
内容的提问来源于stack exchange,提问作者user3044552
相关产品推荐
相关产品推荐

