actuator–基础–05–端点保护
代码位置
https://gitee.com/DanShenGuiZu/learnDemo/tree/master/actuator-learn/actuator01
1、介绍
如果将默认不打开的endpoints打开了,建议一定要加上 Spring security 之类的做 endpoint 保护,避免重要信息外泄。
因为端点的信息和产生的交互都是非常敏感的,必须防止未经授权的外部访问。
2、代码
2.1、依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.2、定义安全校验规则,用来覆盖Spring Security 的默认配置
package fei.zhou.actuator01.security;
/**
* 描述该类
*
* @author <a href="920786312@qq.com">周飞</a>
* @class: ActuatorSecurityConfig
* @date 2022/9/13 19:36
* @Verson 1.0 -2022/9/13 19:36
* @see
*/
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
*
* 定义安全校验规则,用来覆盖Spring Security 的默认配置。
*
* @param null
* @return
* @author <a href="920786312@qq.com">周飞</a>
* @since 2022/9/13 20:00
*/
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
/*
* version1:
*
* 1. 限制 '/shutdown'端点的访问,只允许actuator访问
*
* 2. 允许外部访问其他的端点
*
* 3. 允许外部访问静态资源
*
* 4. 允许外部访问 '/'
*
* 5. 其他的访问需要被校验
*/
// http
// // 允许基于httpServerRequest限制访问
// .authorizeRequests()
// // 限制 '/shutdown'端点的访问,只允许actuator访问
// .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class)).hasRole("ADMIN")
// // 允许外部访问其他的端点
// .requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
// // 允许外部访问静态资源
// .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
// // 允许外部访问 '/'
// .antMatchers("/").permitAll()
// // /**请求,需要用户登录验证
// .antMatchers("/**")
// // 需要用户登录验证
// .authenticated().and()
// // 配置httpBasic验证
// .httpBasic();
/*
* version2:
*
* 1. 限制所有端点的访问,只允许actuator访问
*
* 2. 允许外部访问静态资源
*
* 3. 允许外部访问 '/'
*
* 4. 其他的访问需要被校验 '/'
*/
http
// 允许基于httpServerRequest限制访问
.authorizeRequests()
// Endpoint 请求,需要有ADMIN角色
.requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
// 静态资源 请求,允许访问
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
// /请求,允许访问
.antMatchers("/").permitAll()
// /**请求,需要用户登录验证
.antMatchers("/**")
// 需要用户登录验证
.authenticated().and()
// 配置httpBasic验证
.httpBasic();
}
}
2.3、application.properties
# Spring Security 的 账号,密码,角色
spring.security.user.name=actuator
spring.security.user.password=actuator
spring.security.user.roles=ADMIN
2.4、测试
localhost:8080/actuator/health