Spring Boot Actuator的使用以及安全
组件的引入
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
一个actuator的endpoint需要经过权限的控制(control access),以及对端口进行暴露(expose)才能够进行访问。
control access
默认情况下,除了shutdown和heapdump端点以外,其他所有端点的访问权限都是unrestricted。使用management.endpoint.<id>.access属性去控制端点的访问权限。例子:
management.endpoint.shutdown.access=unrestricted
如果不想要全部权限都是放开的,想到单独的控制每个端点的权限,可以使用如下配置:
management.endpoints.access.default=none
### 单独控制loggers的访问权限
management.endpoint.loggers.access=read-only
Exposing Endpoints
默认情况下,只有health端点通过http和JMX进行暴露。
相关的配置属性:
| Property | Default |
|---|---|
| management.endpoints.jmx.exposure.exclude | |
| management.endpoints.jmx.exposure.include | health |
| management.endpoints.web.exposure.exclude | |
| management.endpoints.web.exposure.include | health |
以下例子暴露了health和info:
management.endpoints.jmx.exposure.include=health,info
*可用来选取所有的端点。
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans
安全
如果在Spring Boot项目的classPath中存在Spring Security依赖,并且在项目中没有自定义的SecurityFilterChain,那么Spring Boot Actuator会自动配置一个SecurityFilterChain,源码在org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration#managementSecurityFilterChain:
@Bean
@Order(SecurityProperties.BASIC_AUTH_ORDER)
SecurityFilterChain managementSecurityFilterChain(Environment environment, HttpSecurity http) throws Exception {
http.authorizeHttpRequests((requests) -> {
//health端点默认开放
requests.requestMatchers(healthMatcher(), additionalHealthPathsMatcher()).permitAll();
requests.anyRequest().authenticated();
});
if (ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet", null)) {
http.cors(withDefaults());
}
http.formLogin(withDefaults());
http.httpBasic(withDefaults());
return http.build();
}
也可以自定义配置SecurityFilterChain:
@Configuration(proxyBeanMethods = false)
public class MySecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.securityMatcher(EndpointRequest.toAnyEndpoint());
http.authorizeHttpRequests((requests) -> requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
http.httpBasic(withDefaults());
return http.build();
}
}
EndpointRequest.toAnyEndpoint()是一个RequestMatcher,用来匹配所有的actuator端点。
参考文档
https://docs.spring.io/spring-boot/reference/actuator/index.html

浙公网安备 33010602011771号