53.3保护HTTP端点
您应该像使用任何其他敏感URL一样注意保护HTTP端点。如果存在Spring安全性,则默认使用Spring安全性内容协商策略来保护端点。例如,
如果您希望为HTTP端点配置自定义安全性,仅允许具有特定角色的用户访问它们,Spring Boot提供了一些方便的 RequestMatcher 对象,可以
与Spring安全性结合使用。
典型的Spring安全配置可能类似于以下示例:
@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();
}
}
上面的示例使用 EndpointRequest.toAnyEndpoint() 将请求与任何端点进行匹配,然后确保所有端点都具有 ENDPOINT_ADMIN 角
色。EndpointRequest 也提供了其他几种匹配方法。
如果在防火墙后部署应用程序,您可能希望无需身份验证即可访问所有执行器端点。您可以通过更
改 management.endpoints.web.exposure.include 属性来执行此操作,如下所示:
application.properties。
management.endpoints.web.exposure.include=*
此外,如果存在Spring安全性,则需要添加自定义安全性配置,以允许对端点进行未经身份验证的访问,如以下示例所示:
@Configuration
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
.anyRequest().permitAll();
}
}
53.4配置端点
端点自动缓存对不带任何参数的读取操作的响应。要配置端点缓存响应的时间量,请使用其 cache.time-to-live 属性。以下示例将 beans 端
点缓存的生存时间设置为10秒:
application.properties。
management.endpoint.beans.cache.time-to-live=10s
前缀 management.endpoint.<name> 用于唯一标识正在配置的端点。
在进行经过身份验证的HTTP请求时, Principal 被视为端点的输入,因此不会缓存响应。
53.5用于执行器Web端点的超媒体
添加了“发现页面”,其中包含指向所有端点的链接。默认情况下, /actuator 上提供了“发现页面”。
配置自定义管理上下文路径后,“发现页面”会自动从 /actuator 移动到管理上下文的根目录。例如,如果管理上下文路径为 /management ,
则可以从 /management 获取发现页面。当管理上下文路径设置为 / 时,将禁用发现页面以防止与其他映射冲突的可能性。
53.6 CORS支持
跨源资源共享 (CORS)是一种W3C规范,允许您以灵活的方式指定授权的跨域请求类型。如果您使用Spring MVC或Spring WebFlux,可以
配置Actuator的Web端点以支持此类方案。
默认情况下禁用CORS支持,仅在设置了 management.endpoints.web.cors.allowed-origins 属性后才启用CORS支持。以下配置允许来
自 example.com 域的 GET 和 POST 来电:
management.endpoints.web.cors.allowed-origins=http://example.com
management.endpoints.web.cors.allowed-methods=GET,POST
53.7实现自定义端点
如果添加注释为 @Endpoint 的 @Bean ,则使用 @ReadOperation , @WriteOperation 或 @DeleteOperation 注释的任何方法都会通过JMX自
动公开,并且在Web应用程序中也会通过HTTP自动公开。可以使用Jersey,Spring MVC或Spring WebFlux通过HTTP公开端点。
您还可以使用 @JmxEndpoint 或 @WebEndpoint 编写特定于技术的端点。这些端点仅限于各自的技术。例如, @WebEndpoint 仅通过HTTP而不
是通过JMX公开。
您可以使用 @EndpointWebExtension 和 @EndpointJmxExtension 编写特定于技术的扩展。通过这些注释,您可以提供特定于技术的操作来扩
充现有端点。
最后,如果您需要访问特定于Web框架的功能,您可以实现Servlet或Spring @Controller 和 @RestController 端点,但代价是它们无法通过
JMX或使用不同的Web框架。