spring boot actuator 安全配置 springboot的安全性

本文详细介绍了如何在SpringBootActuator框架中配置安全措施,包括添加security验证、处理URL请求权限、启用/禁用特定端点以及跨域请求的管理。两种方案分别涉及全局权限控制和定制化端点配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于springboot Actuator框架的安全配置方案:

加入security安全验证框架

方案一:

配置信息:

spring:
    security:
        user:
          password: admin
          name: admin

management:
  endpoints:
    web:
      base-path: /monitor
      exposure:
        include: "*"
        # 排除端点
        exclude: shutdown
  server:
    port: 9595
  endpoint:
    health:
      show-details: always
    shutdown:
      enabled: true

引入依赖信息

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

需要上下午url对进行处理;

处理方法一:只针对端点请求进行权限校验

@Configuration
@EnableWebSecurity
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  Environment env;

  @Override
  protected void configure(HttpSecurity security) throws Exception {
        String contextPath = env.getProperty("management.endpoints.web.base-path");
        if(StringUtils.isEmpty(contextPath)) {
            contextPath = "";
        }
        security.csrf().disable().headers().frameOptions().disable();
        security.cors().and().antMatcher("/**"+contextPath+"/**")
				.authorizeRequests()
				.anyRequest()
                .authenticated().and().httpBasic();
     }
}

以下处理跨域请求

@Configuration
public class WebConfig implements WebMvcConfigurer {

	/**
	 * 允许跨域请求
	 *
	 * @param registry
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
			.allowedOrigins("*")
			.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
			.allowCredentials(true)
			.maxAge(3600)
			.allowedHeaders("*");
	}

	@Bean
	CorsConfigurationSource corsConfigurationSource() {
		CorsConfiguration configuration = new CorsConfiguration();
		configuration.setAllowedOrigins(Arrays.asList("*"));
		configuration.setAllowedMethods(Arrays.asList("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"));
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", configuration);
		return source;
	}
}

方案二:定制端点信息

**启用端点:**默认情况下,启用除shutdown 之外的所有端点。要配置端点的启用,请使用其management.endpoint…enabled 属性。以下示例启用shutdown 端点:

management.endpoint.shutdown.enabled=true
management.endpoint.env.enabled=false

如果您希望端点启用是选择加入而不是选择退出,请将management.endpoints.enabled-by-default 属性设置为false 并使用单个端点enabled 属性重新加入。以下示例启用info endpoint并禁用所有其他端点:

management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值