核心是控制端点暴露与安全访问权限:通过management.endpoints.web.exposure.include按需指定端点id(禁用*),敏感详情设show-details: when_authorized;再用spring security的securityfilterchain精确匹配路径并限制角色(如hasrole("admin")),高危端点须认证,低风险端点可permitall,并关闭threaddump、heapdump等调试端点。

Java 中配置 Actuator 端点暴露与安全访问权限,核心是两件事:**控制哪些端点可见(暴露)**,以及**限制谁可以访问(授权)**。两者缺一不可,否则容易造成敏感信息泄露或未授权操作。
端点暴露控制:用配置文件决定“开哪些门”
Actuator 默认只暴露 /actuator/health 和 /actuator/info 两个基础端点。如需启用其他端点(包括自定义端点),必须显式声明:
- 在
application.yml中:
management:
endpoints:
web:
exposure:
include: "health,info,metrics,env,custom" # 列出要暴露的端点ID,* 表示全部(不推荐生产使用)
endpoint:
health:
show-details: when_authorized # 敏感详情仅对认证用户展示
custom:
enabled: true # 确保自定义端点本身已启用
-
include推荐按需填写具体 ID,避免用*;env、beans、threaddump等高危端点应默认禁用 -
show-details: when_authorized是关键项——它让/actuator/health在未认证时只返回{"status":"UP"},认证后才显示详细组件状态
安全访问控制:用 Spring Security 决定“谁有钥匙”
暴露 ≠ 公开。即使端点已启用,也必须通过 Spring Security 设置访问规则。推荐使用 SecurityFilterChain(Spring Boot 2.7+ 标准方式):
- 只允许 ADMIN 角色访问自定义端点
/actuator/custom:
@Configuration
@EnableWebSecurity
public class ActuatorSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/actuator/custom").hasRole("ADMIN")
.requestMatchers("/actuator/health", "/actuator/info").permitAll()
.requestMatchers("/actuator/**").authenticated()
)
.httpBasic(); // 启用 HTTP Basic 认证(也可换成 JWT 或表单登录)
return http.build();
}
}
- 路径匹配要精确:
/actuator/custom不等于/actuator/custom-endpoint,ID 名必须和@Endpoint(id = "custom")一致 - 把低风险端点(如 health/info)设为
permitAll,便于健康探针调用;高风险端点(如 env/shutdown)必须authenticated或更严格 - 务必启用某种认证方式(
httpBasic()、formLogin()或 OAuth2 Resource Server)
自定义端点内嵌校验:补充运行时动态判断
当权限逻辑较复杂(比如按 IP 段、租户 ID 或请求参数动态放行),可在端点方法内部做二次校验:
- 在自定义端点类中注入
SecurityContext:
@Endpoint(id = "custom")
public class CustomEndpoint {
@ReadOperation
public Map<string object> getStatus() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || !auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_OPERATOR"))) {
throw new AccessDeniedException("Insufficient authority");
}
return Map.of("status", "OK", "data", "sensitive-info");
}
}
</string>- 这种方式适合细粒度业务规则,但不能替代 Web 层拦截——它无法阻止非法请求到达端点方法
- 注意:抛出
AccessDeniedException会触发 Spring Security 的拒绝处理机制(如返回 403)
生产环境必须检查的 3 个细节
-
关闭调试端点:确认
management.endpoint.threaddump.enabled=false、management.endpoint.heapdump.enabled=false,防止内存快照泄露 -
绑定内网地址:设置
management.server.address=127.0.0.1,让 Actuator 只监听本地回环,配合反向代理统一鉴权 -
角色命名规范:Spring Security 的
hasRole("ADMIN")实际匹配的是ROLE_ADMIN权限(自动加前缀),确保用户权限中包含完整字符串
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











