likes
comments
collection
share

小白学习SpringBoot Admin集成security,实现Actuator端点可视化监控

作者站长头像
站长
· 阅读数 27

搭建

spring-admin-server

  1. 使用spring.initializr创建一个新的springboot项目,项目取名为spring-admin-server

  2. 项目依赖

  • spring-boot-admin-starter-server:版本2.7.3
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>cn.server.boot</groupId>
    <artifactId>spring-admin-server</artifactId>
    <version>1.0.0</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 实现对 Spring Boot Admin Server 的自动化配置 -->
        <!--
            包含 1. spring-boot-admin-server :Server 端
                2. spring-boot-admin-server-ui :UI 界面
                3. spring-boot-admin-server-cloud :对 Spring Cloud 的接入
        -->
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.7.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>

</project>
  1. 启动类,添加@EnableAdminServer注解
package cn.server.boot;

import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@EnableAdminServer
@SpringBootApplication
public class AdminServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(AdminServerApplication.class, args);
    }

}
  1. 开启security鉴权,去除关于我们,修改网站标题,配置全局上下文路径
  • 配置application.yaml
spring:
  boot:
    admin:
      ui:
        view-settings:
        # 去除关于我们
          - name: 'about'
            enabled: false
        # 修改登录标题
        title: 日志监控
        # 修改左上角标题
        brand: <img src="assets/img/icon-spring-boot-admin.svg"><span>${spring.boot.admin.ui.title}</span>
      context-path: /admin
  security:
  # security的登录用户名:admin,密码:admin
    user:
      password: admin
      name: admin
  • 添加 Spring Security 认证路由
package cn.server.boot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

import de.codecentric.boot.admin.server.config.AdminServerProperties;

@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
    private final String adminContextPath;

    public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(adminContextPath + "/");
        // 永远使用defaultTargetUrl,否则会导致第一次访问未携带context-path,登陆后,不携带context-path
        successHandler.setAlwaysUseDefaultTargetUrl(alwaysUseDefaultTargetUrl);
        
        http.authorizeRequests().antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers(adminContextPath + "/login").permitAll().anyRequest().authenticated().and().formLogin()
                .loginPage(adminContextPath + "/login").successHandler(successHandler).and().logout()
                .logoutUrl(adminContextPath + "/logout").and().httpBasic().and().csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringAntMatchers(adminContextPath + "/instances", adminContextPath + "/actuator/**");
    }
}
  1. 访问localhost:8080 小白学习SpringBoot Admin集成security,实现Actuator端点可视化监控

输入配置的用户信息后, 登录后发现, 页面是空的, 即没有任何应用注册上来!这时, 由于管理端开启了认证, 那么客户端要想注册上来, 也必须提供认证信息。

在客户端的 application.yml 中(注意, 是在客户端的配置文件)添加: 小白学习SpringBoot Admin集成security,实现Actuator端点可视化监控

最后, 登录管理端 http://localhost:8080 , 成功后的信息如下, 注意右上角的用户信息:

小白学习SpringBoot Admin集成security,实现Actuator端点可视化监控

Spring Boot Admin Client

  1. 使用spring.initializr创建一个新的springboot项目,项目取名为spring-admin-client

  2. 项目依赖

  • spring-boot-admin-starter-client:版本为2.7.3
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>cn.client.boot</groupId>
    <artifactId>spring-admin-client</artifactId>
    <version>1.0.0</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- 实现对 Spring MVC 的自动化配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 实现对 Actuator 的自动化配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- 实现对 Spring Boot Admin Client 的自动化配置 -->
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.7.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>

</project>
  1. 配置application.yml
  • 暴露指定端口
server:
  port: 18080 # 设置自定义 Server 端口,避免和 Spring Boot Admin Server 端口冲突。

management:
  endpoint:
    health:
      show-details: always
  endpoints:
    # Actuator HTTP 配置项,对应 WebEndpointProperties 配置类
    web:
      exposure:
        include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
        exclude: env,beans
  • 配置security的鉴权用户名和密码,注册到Spring Boot Admin服务端
spring:
  security:
  # security的鉴权用户名和密码
    user:
      name: user
      password: password
  application:
    name: admin-client # 应用名
  boot:
    admin:
    # 客户端注册到服务端
      client:
        url: http://127.0.0.1:8080/admin # Spring Boot Admin Server 地址
        instance:
          name: ReactiveCrud

这里首先要开启项目的Actuator端点监控功能

  • 如果不配置metadatauser.nameuser.password,会发现获取到的数据并不完整,是因为客户的应用虽然注册到了管理端, 但是管理端并未获得客户端的认证。 小白学习SpringBoot Admin集成security,实现Actuator端点可视化监控

  • 在 application.yml 中增加当前实例注册到管理端的认证信息, 主要是metadata下的 user.name 与 user.password

spring:
  security:
  # security的鉴权用户名和密码
    user:
      name: user
      password: password
  application:
    name: admin-client # 应用名
  boot:
    admin:
    # 客户端注册到服务端
      client:
        url: http://127.0.0.1:8080/admin # Spring Boot Admin Server 地址
        instance:
          name: ReactiveCrud
          metadata: # 这个name与password用于在注册到管理端时,使管理端有权限获取客户端端点数据
            user.name: ${spring.security.user.name}
            user.password: ${spring.security.user.password}
        # 服务端的security的用户名和密码
        username: admin
        password: admin

小白学习SpringBoot Admin集成security,实现Actuator端点可视化监控

  • SpringBoot2开启Actuator端点监控
  1. 首先集成依赖spring-boot-starter-actuator
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

直接运行项目, 在后端控制台会看到以下输出:

2024-05-19 10:49:24.390 INFO 20604 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 11 endpoint(s) beneath base path '/actuator'

  1. 访问 http://localhost:18080/actuator , 结果如下:

小白学习SpringBoot Admin集成security,实现Actuator端点可视化监控

  • 虽然端点 enabled , 但是还需要 exposed , 才能在Web端访问;
  • health 端点在默认情况下, 仅显示 "status": "UP" ; 如需显示详细信息, 配置: management.endpoint.health.show-details=always
  • 实际中, 请谨慎选择要开启的端点!

参考

转载自:https://juejin.cn/post/7369993845750136883
评论
请登录