一、集成Security
- spring-boot-admin-server-ui提供登录页面和注销按钮。结合 Spring Security 实现需要用户名和密码登录的安全认证。
- 核心配置和代码
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
application.yml
spring:
security:
user:
name: admin
password: admin
eureka:
# 配置 spring security 的用户名和密码,这时需要在服务注册时带上 metadata-map 的信息。
metadata-map:
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
SecurityConfig
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 SecurityConfig extends WebSecurityConfigurerAdapter {@Override
protected void configure(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler
= new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl("/");http.authorizeRequests()
//授予公众对所有静态资产和登录页面的访问权限。
.antMatchers("/assets/**").permitAll()
//登陆页面排除
.antMatchers("/login").permitAll()
// 其他所有请求都必须经过验证。
.anyRequest().authenticated().and()
.formLogin().loginPage("/login")
.successHandler(successHandler).and()
.logout().logoutUrl("/logout").and()
.httpBasic().and()
.csrf()
// 使用Cookies启用CSRF保护
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
//对执行器端点禁用CSRF-Protection。
.ignoringAntMatchers(
"/instances",
"/actuator/**"
);
}
}
- 效果
二、集成通知
- 邮件通知
Admin Server服务中,添加邮件相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
新增相关配置项
spring.mail.host=smtp.qq.com
# to和from都要配置,否则发送邮件时会报错
spring.boot.admin.notify.mail.to=263527944@qq.com
spring.boot.admin.notify.mail.from=263527944@qq.com# 邮件的用户名和授权码
spring.mail.username=123@qq.com
spring.mail.password=123
启动报错
Caused by: javax.mail.AuthenticationFailedException:
535 Login Fail. Please enter your authorization code to login.
More information in http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
1.2.1、获取授权码
修改
spring.mail.password=zxs1aw1wbgpnreb4dbh
1重新启动,发现成功了
- 自定义通知
方式
实现Notifier接口
通过扩展AbstractEventNotifier或AbstractStatusChangeNotifier
核心代码
CustomNotifier
package fei.zhou.adminserver2.config;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent;
import de.codecentric.boot.admin.server.notify.AbstractStatusChangeNotifier;
import de.codecentric.boot.admin.server.notify.LoggingNotifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;/**
* 描述该类- JPA
*
* @author zhoufei
* @class: CustomNotifier
* @date 2021/5/20 11:20
* @Verson 1.0 -2021/5/20 11:20
* @see
*/
@Component
public class CustomNotifier extends AbstractStatusChangeNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger( LoggingNotifier.class);public CustomNotifier(InstanceRepository repository) {
super(repository);
}@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
return Mono.fromRunnable(() -> {
if (event instanceof InstanceStatusChangedEvent) {
LOGGER.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(),
((InstanceStatusChangedEvent) event).getStatusInfo().getStatus());String status = ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus();
switch (status) {
// 健康检查没通过
case "DOWN":
System.out.println("发送 健康检查没通过 的通知!");
break;
// 服务离线
case "OFFLINE":
System.out.println("发送 服务离线 的通知!");
break;
//服务上线
case "UP":
System.out.println("发送 服务上线 的通知!");
break;
// 服务未知异常
case "UNKNOWN":
System.out.println("发送 服务未知异常 的通知!");
break;
default:
break;
}} else {
LOGGER.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(),
event.getType());
}
});
}
}
2.3、效果
admin-client2 关闭服务,在重启服务
三、集成日志配置
- 介绍
默认情况下,日志文件无法通过执行器端点访问,因此在Spring Boot Admin中不可见。
为了启用日志文件执行器端点,可以这样做
或者 设置logging.file.path
或者 将Spring Boot配置为写入日志文件 logging.file.name。
- 操作
logging:
file:
# 日志来源文件 日志
path: D:\\log
# # 日志来源文件 格式
pattern:
file: '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx'
四、单独集成Security
- 服务器安全
核心配置和代码
pom.xml
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
application.yml
# 应用程序名称
spring:
application:
name: admin-server
security:
user:
name: admin-server
password: admin-server
# 应用程序端口
server:
port: 8080
SecurityConfig
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 SecurityConfig extends WebSecurityConfigurerAdapter {@Override
protected void configure(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler
= new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl("/");http.authorizeRequests()
//授予公众对所有静态资产和登录页面的访问权限。
.antMatchers("/assets/**").permitAll()
//登陆页面排除
.antMatchers("/login").permitAll()
// 其他所有请求都必须经过验证。
.anyRequest().authenticated().and()
.formLogin().loginPage("/login")
.successHandler(successHandler).and()
.logout().logoutUrl("/logout").and()
.httpBasic().and()
.csrf()
// 使用Cookies启用CSRF保护
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
//对执行器端点禁用CSRF-Protection。
.ignoringAntMatchers(
"/instances",
"/actuator/**"
);
}
}
AdminServer2Application
//开启 Admin 的 Server
@EnableAdminServer
@SpringBootApplication
public class AdminServer2Application {
public static void main(String[] args) {
SpringApplication.run(AdminServer2Application.class, args);
}
}
1.2、效果
- 客户端安全
核心配置和代码
pom.xml
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.3.1</version>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
application.yml
# 应用程序名称
spring:
application:
name: admin-client
# 登陆的用户密码
security:
user:
name: admin-client
password: admin-client
boot:
# 要在其中注册的Spring Boot Admin Server的URL。
admin:
client:
url: http://localhost:8080
instance:
# 使用IP的方式
prefer-ip: true
metadata:
user:
# admin server 将使用这些凭据对客户端的Actuator端点进行身份验证
name: ${spring.security.user.name}
password: ${spring.security.user.name}
# admin server 的用户密码, admin-client 通过这些凭据, 向admin server服务器注册:
username: admin-server
password: admin-server
# 应用程序端口
server:
port: 9090
# 默认情况下,大多数Actuator端点都不通过http公开,这里我们公开了所有端点。
# 对于生产,您应该仔细选择要公开的端点。management:
endpoints:
web:
exposure:
include: ["*"]
2.2、效果
五、按应用实例添加标签
Tags 是我们区别同一应用的不同实例的方法
- 举例
监控spring.application.name=admin-client 应用的三个实例,分别是
开发(dev)
测试(test)
生产(prod)
使用信息端点/info
info:
tags:
environment: dev
或者这样配置
spring:
boot:
admin:
client:
instance:
metadata:
tags:
environment: dev
1.2、效果