惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
Jina AI
Jina AI
雷峰网
雷峰网
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI
博客园 - 司徒正美
罗磊的独立博客
J
Java Code Geeks
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
Vercel News
Vercel News
A
About on SuperTechFans
I
InfoQ
D
DataBreaches.Net
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
aimingoo的专栏
aimingoo的专栏
宝玉的分享
宝玉的分享
P
Proofpoint News Feed
Microsoft Azure Blog
Microsoft Azure Blog
美团技术团队

小松鼠的博客

记录一次线上k8s工作节点无法创建容器的问题排查思路与解决办法 记一次线上GoLang项目OOM排查过程 从LastPass转向拥抱开源KeePass的心路历程 故障定位与 AI 结合前后端编码实践 FileBeat收集nginx-ingress-controller日志 K8s云原生环境下文件描述符占用过高查询思路 2024年最新关闭火绒安全工具的开机自启方法 Kubernetes任务调度实践-Go语言实现Job和CronJob对比分析 离线更新k8s环境下的trivy漏洞库方法 使用Go语言接入Choerodon实现基于OAuth2的统一身份认证登录 在Vue2中自定义Switch组件并实现父子组件双向数据绑定 关于docker jdk1.8镜像中的GB18030-2022标准支持及验证 Go框架gin中的session存储gin-contrib-sessions和go-session 关于修改node_module中的源码问题记录 docker-compose网络和内网服务IP冲突问题 慎用存储过程:一条语句引发的数据库存储100%占用 Spring Boot中4种文件下载方法的实现 避坑-不能将specific类型的gitlab-runner改变为share类型 Docker compose中的MySQL主从复制模式和percona-toolkit工具使用 在minio中开启https访问以及使用rclone备份minio桶 在多机Docker环境下部署Choerodon的解决方案 在Nginx的容器镜像中隐藏Nginx的Server响应头 K8s中的两种nginx-ingress-controller及其区别 两个docker工具:runlike和whaler Grafana中的邮件报警和截图插件grafana-image-enderer K8s中externalName-service和services-without-selectors maven配置文件settings.xml中的一些概念总结 K8s中flexvolume插件驱动的安装 K8s中的coredns无法解析svc问题排查 K8s中使用Ingress访问请求体过大问题解决
Prometheus中Monitor添加对SpringBoot Actuator的Basic认证
ycyin · 2023-02-19 · via 小松鼠的博客

2023年2月18日大约 3 分钟云原生PrometheusSpring Boot


一般地,我们使用Prometheus对SpringBoot应用进行监控时,没有做任何认证,监控接口是完全开放的,我们直接访问暴露出来的指标接口http://localhost:8081/actuator/prometheus就可以拿到指标接口,这在某些程度上不安全。。

我们需要给我们的监控指标接口添加一个Base认证。

应用添加Basic认证

我这里是SpringBoot2.3.9版本,在添加spring-boot-starter-actuator和micrometer-registry-prometheus做指标暴露外,还在此基础之上还需要添加spring-boot-starter-security包。

<!-- 监控检查及度量 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
	<groupId>io.micrometer</groupId>
	<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

添加配置类以拦截指标暴露Endpoint端口,ENDPOINT_ADMIN角色可自定义:

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration(proxyBeanMethods = false)
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {

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

}

添加配置:

management:
  server:
    port: 8081
  endpoints:
    web:
      exposure:
        include: "*"

spring:
  security:
    user:
      name: admin
      password: admin
      roles: ENDPOINT_ADMIN

默认情况下,health健康检查端口不会被认证拦截,如需要添加,还需要如下配置

management:
  endpoint:
    health:
      roles: ENDPOINT_ADMIN

这时候就添加了认证,再次访问指标接口就需要添加Basic认证了。

curl -u admin:admin http://192.168.96.196:8081/actuator/prometheus

Prometheus采集指标添加认证

我们的Prometheus采用Operator安装,所以只需要修改PodMonitor和ServiceMonitor就可以了。如果没有使用Operator可能需要修改Prometheus本身的job,可参考:https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config

添加一个Secret存储密码:

Secret中有两个key分别是username和password,值是对应的明文Base64后的。

apiVersion: v1
kind: Secret
metadata:
  name: basic-auth
  namespace: metric-yyc
data:
  password: YWRtaW4= # base64 字符串 admin
  username: YWRtaW4= 

修改ServiceMonitor:

在spec.endpoints下添加basicAuth,如下:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  labels:
    yyc: app
  name: service-out
  namespace: metric-yyc
spec:
  endpoints:
  - interval: 10s
    path: /metrics
    port: metric
    basicAuth: # 添加认证
      password:
        name: basic-auth
        key: password
      username:
        name: basic-auth
        key: username
    relabelings:
    - action: replace
      regex: ([^:]+)(?::\d+)?;(\d+)
      replacement: $1:$2
      sourceLabels:
      - __address__
      - __meta_kubernetes_service_annotation_prometheus_io_port
      targetLabel: __address__
    - action: replace
      regex: (.*)
      replacement: $1
      sourceLabels:
      - __meta_kubernetes_service_annotation_prometheus_io_path
      targetLabel: __metrics_path__
  namespaceSelector:
    matchNames:
    - app-yyc # 需要选择的namespace
  selector:
    matchLabels:
      prometheus.io/scrape: "true"
      yyc.metric.auth: "true" # 自定义一个label用于匹配需要认证的service

修改PodMonitor:

在spec.podMetricsEndpoints下添加basicAuth,如下:

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  labels:
    yyc: app
  name: pod-out
  namespace: metric-yyc
spec:
  namespaceSelector:
    matchNames:
    - app-yyc # 需要选择的namespace
  podMetricsEndpoints:
  - interval: 15s
    path: /actuator/prometheus
    port: metric
    basicAuth: # 添加认证
      password:
        name: basic-auth
        key: password
      username:
        name: basic-auth
        key: username
    relabelings:
    - action: replace
      regex: ([^:]+)(?::\d+)?;(\d+)
      replacement: $1:$2
      sourceLabels:
      - __address__
      - __meta_kubernetes_pod_annotation_prometheus_io_port
      targetLabel: __address__
    - action: replace
      regex: (.*)
      replacement: $1
      sourceLabels:
      - __meta_kubernetes_pod_annotation_prometheus_io_path
      targetLabel: __metrics_path__
  selector:
    matchLabels:
      prometheus.io/scrape: "true"
      yyc.metric.auth: "true" # 自定义一个label用于匹配需要认证的service

这样Prometheus就可以在采集数据指标时自动加上Base认证了。

这里遇到一个坑就是Prometheus Operator在较低的版本中的PodMonitor不支持basicAuth字段,注意查看对应版本prometheus-operator-crd的定义[^1]。

参考:

1:https://www.amitph.com/how-to-secure-spring-boot-actuator-endpoints/

2:https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/user-guides/basic-auth.md

3:https://github.com/prometheus-operator/prometheus-operator/tree/main/example/prometheus-operator-crd

4: Spring Boot Actuator https://blog.csdn.net/weixin_50518271/article/details/111183826https://blog.csdn.net/weixin_50518271/article/details/111237298