Spring Boot Admin提供了可视化的监控服务,通过Spring Security的机制保护管理端点,以保证监控数据的安全性。可以使用Spring Security添加认证和授权功能,例如基于用户角色的访问控制、登录页面、注销等。需要配置Spring Security的相关依赖,并在配置文件中设置安全属性。可以使用默认的用户名和密码进行登录,并为管理员用户配置访问授权。Spring Boot Admin还提供了自定义登录页面的功能,以便更好地满足实际需求。
在本教程开启之前,需要先进行SpringBoot-Admin项目的搭建和开启,并在需要被检控的客户端引入spring-boot-admin-client包,并填写相关配置参数。具体步骤可以参考我的上篇文章:SpringBoot-开启Admin监控服务。
一、pom.xml 引入 security 包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
添加完依赖后,刷新maven自动导入jar包。
二、SBA项目(服务端)的 application.yml 里增加 security 配置
spring:
#开启安全认证 用户名和密码
security:
user:
name: "root"
password: "root"
三、SBA项目(服务端)增加 SecuritySecureConfig 类
package com.config;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
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;
@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 + "/");
http.authorizeRequests()
.antMatchers(adminContextPath + "/assets/**").permitAll()
.antMatchers(adminContextPath + "/login").permitAll()
.antMatchers(adminContextPath+"/actuator/health").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/**"
);
}
}
四、被监控项目(客户端)的 application.yml 里增加 security 连接信息
spring:
application:
## 注册服务名
name: ProjectSchedule
# springbootAdmin
boot:
admin:
client:
url: http://127.0.0.1:8088
username: 'root'
password: 'root'
jackson:
serialization:
indent_output: true
五、测试改动后的变化及是否连接成功
1、服务端访问,需要输入账号密码
2、服务端看到客户端的在线信息
说明连接成功!Security机制顺利开启!
Damon, Chinese, Liu Guangzhi, Software development engineer, CSDN quality creator, Ali Cloud expert blogger, Microsoft Technology Associate, Good at C#, Java, PHP, Python, etc, Love sports, Workaholic, Communist.