如何使用 spring boot 2 以编程方式获取所有执行器端点?

How to get all actuator endpoints programatically using spring boot 2?

在 spring 引导中 1.x 可以通过编程方式解析所有执行器端点。我有一个公开所有执行器端点路径的 bean

@Component
public class MyProjectActuatorEndpoints {

    @Autowired
    private MvcEndpoints endpoints;

    public String[] getActuatorEndpointPaths() {
        return endpoints.getEndpoints().stream()
            .map(MvcEndpoint::getPath)
            .map(path -> path + "/**")
            .toArray(String[]::new);
    }
}

不幸的是,在 spring boot actuator 2.0.5.RELEASE 中没有这样的 class MvcEndpoints。在新的 spring 版本中,这个 class 是否有任何替代品?

Spring Boot Actuator 2.x 将 /actuator 端点公开为可配置的环境变量。

启用执行器端点

您可以在 application.properties

中启用这些 actuator endpoints
management.endpoints.web.exposure.include=info, health

或(极其谨慎地)启用它们。请记住,其中许多本质上是敏感的。

management.endpoints.web.exposure.include=*

保护执行器端点 (reference)

文档将此指定为保护所有端点的策略。 EndpointRequest 本身将是最接近您要查找的内容的替代项 (MvcEndpoints)

@Configuration
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
            .anyRequest().hasRole("ENDPOINT_ADMIN")
            .and()
            .httpBasic();
    }

}

您还可以设置一个特定的 antmatcher,以防您有不同的策略或角色想要分配给这些端点

httpRequest.authorizeRequests().antMatcher("/actuator/*").hasRole("ENDPOINT_ADMIN")

您需要的一切都在 org.springframework.boot.actuate.endpoint.web.PathMappedEndpoints bean 中。如果您原谅双关语,这应该会让您走上正确的道路:

@Slf4j
@Component
public class ActuatorLogger {

  public ActuatorLogger(@Autowired PathMappedEndpoints pme) {
    log.info("Actuator base path: {}", pme.getBasePath());
    pme.getAllPaths().forEach(p -> log.info("Path: {}", p));
  }
}

org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest 可用于帮助您在需要从代码执行操作时为执行器端点设置 spring 安全规则。例如,在您的 WebSecurityConfigurerAdapter 实施中,此片段可以合并到您现有的规则中:

http.authorizeRequests()
      .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class))
      .hasAnyAuthority("ROLE_ADMIN", "ROLE_SUPPORT")
@Autowired
private HealthEndpoint healthEndpoint;

public Health getAlive() {
    return healthEndpoint.health();
}