SpringBoot Actuator refresh/bus-refresh访问返回401/403问题
核心问题根因
- 路径匹配不生效:原有配置中
/refresh/、/bus-refresh/的末尾斜杠,在Spring Boot 2.6+默认关闭尾随斜杠兼容的规则下,无法匹配实际请求的无斜杠路径;而/health未加斜杠,和实际路径完全匹配,因此访问正常 - CSRF拦截触发403:两个端点仅支持POST请求触发,Spring Security默认开启的CSRF防护会拦截无合法CSRF Token的POST请求,返回的错误格式和遇到的403响应完全一致;GET请求不受CSRF规则约束,因此health端点可以正常返回
- 权限匹配兜底:因为前两个路径没有命中permitAll规则,最终请求落入
anyRequest().authenticated()的拦截范围,被OAuth2资源服务器的未认证规则拦截
可落地修复步骤
1. 修正权限路径匹配规则
将原有带末尾斜杠的路径配置调整为和实际访问路径完全一致的形式,旧版本Spring Security配置示例:
http .anonymous() .and() .authorizeRequests() .antMatchers( "/swagger-ui.html", "/error", "/swagger-resources/**", "/webjars/**", "/v2/api-docs", "/test/**", "/api/v1/calculate/**", "/health", "/refresh", "/bus-refresh" ).permitAll() .anyRequest().authenticated() .and() .oauth2ResourceServer();
如果使用Spring Security 5.7+版本,替换掉已废弃的antMatchers,使用新的API:
http .anonymous() .and() .authorizeHttpRequests(auth -> auth .requestMatchers( "/swagger-ui.html", "/error", "/swagger-resources/**", "/webjars/**", "/v2/api-docs", "/test/**", "/api/v1/calculate/**", "/health", "/refresh", "/bus-refresh" ).permitAll() .anyRequest().authenticated() ) .oauth2ResourceServer();
2. 对POST类Actuator端点排除CSRF校验
因为这类端点是服务间/CI工具的无状态调用,不需要CSRF防护,直接在配置中排除两个路径的CSRF校验,新版本写法示例:
http.csrf(csrf -> csrf.ignoringRequestMatchers("/refresh", "/bus-refresh"));
旧版本写法:
http.csrf().ignoringAntMatchers("/refresh", "/bus-refresh");
3. 常见遗漏校验项
- 核对application.yml配置:当前
base-path: /的配置正确,不会让端点嵌套在/actuator路径下,如果后续修改base-path,权限配置需要同步调整对应路径 - 确认暴露规则:
include: health,refresh,bus-refresh的配置正确,没有漏写端点标识 - 正确的请求方式:两个端点默认仅支持POST请求,验证用的curl命令格式为:
curl -X POST http://localhost:8080/bus-refresh curl -X POST http://localhost:8080/refresh
4. 高版本兼容补充
如果使用Spring Cloud 2021.0.x及以上版本,内置的Actuator安全配置优先级高于自定义Security配置,需要给自定义的Security配置类添加注解@Order(Ordered.HIGHEST_PRECEDENCE),确保自定义的公开路径规则先生效,不会被内置规则覆盖。
内容的提问来源于stack exchange,提问作者Arun
相关产品推荐
相关产品推荐

