欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > Spring Boot Actuator基础使用及Actuator未授权访问处理

Spring Boot Actuator基础使用及Actuator未授权访问处理

2025/5/14 18:37:49 来源:https://blog.csdn.net/weixin_43625238/article/details/146934493  浏览:    关键词:Spring Boot Actuator基础使用及Actuator未授权访问处理

SpringBoot项目引入Actuator监控

  • pom.xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId><version>2.7.13</version>
</dependency>
  • bootstrap.yml
management:server:#管理端口port: 8091endpoints:web:exposure:#暴露的端点,*表示全部,如果想要开放指定的端点,可以以逗号分割,指定开放,如info,health就表示开放info,health两个端点include: '*'
  • 测试
    启动后访问本地actuator端点列表接口 http://127.0.0.1:8091/actuator
    actuator端点列表
    访问一个开放的端点,如health
    health端点.png

代码定位

以health为例,health的端点实现方法为org.springframework.boot.actuate.health.HealthEndpoint#health()

@ReadOperation
public HealthComponent health() {HealthComponent health = this.health(ApiVersion.V3, EMPTY_PATH);return (HealthComponent)(health != null ? health : DEFAULT_HEALTH);
}

其余端点可以去org.springframework.boot.actuate包下对应端点的包名中寻找响应的Endpoint类即可

自定义端点扩展

  • 新建hello的endpoint
@Component
@Endpoint(id = "hello")
public class HelloEndpoint {@ReadOperationpublic String hello() {return "hello";}
}
  • 运行项目,访问 http://127.0.0.1:8091/actuator
    发现hello端点出现在列表中
    actuator
  • 访问hello端点 http://127.0.0.1:8091/actuator/hello
    自定义端点

添加认证

在实际的项目中,如果未进行特殊处理,actuator往往会触发Actuator未授权访问漏洞,
这种时候需要进行修复,下面推荐几种修复方式

  • 借助security进行授权
    pom中引入security的依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>

编写认证代码

@Configuration
@Order(66)
public class SecurityConfiguration {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.csrf().disable()// 配置对/actuator/的请求进行拦截.authorizeRequests()// 仅允许10.9网段及本地访问端点.antMatchers("/actuator/**").access("hasIpAddress('10.9.0.0/16') or hasIpAddress('127.0.0.1')").and()// 配置一个自定义的访问拒绝处理器(可选,但推荐用于明确的403响应).exceptionHandling().accessDeniedHandler((request, response, accessDeniedException) -> response.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not allowed to access!"));return http.build();}
}

访问 http://127.0.0.1:8091/actuator
,发现可正常返回
127网段访问
访问 http://10.8.0.46:8091/actuator
,返回403
10.8网段

  • 仅开放部分端点
    在部分要求不严格的环境中,可以只开放部分不敏感的端点,如
management:server:port: 8091endpoints:web:exposure:include: health,info

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词