简介
SpringCloud-admin作为微服务服务监控平台,当被监控服务注册到admin后,admin会定期获取健康信息,此时部分被监控服务可能有security安全校验,在获取健康信息时就会出现Unauthorized 401等类似响应值。网上大多数解决方案是management.security.enabled=false,该方式虽然可以临时解决,但不是长久之计。
分析
出现Unauthorized 401的本质在于被监控服务开启了security安全校验(spring-boot-starter-security),而admin获取信息时只是取/actuator/**下的信息,因此只需要在被监控服务中让security安全校验放过/actuator/**即可。
在被监控服务中添加如下配置
http.authorizeRequests().antMatchers("/actuator/**").permitAll();
全代码(根据自己的security安全配置文件酌情修改)
/**
* 添加security依赖后要通过该类开启校验
*
* @创建人 Wang Bintao
* @创建时间 2019/12/13
* @描述
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 只开启eureka注册账密校验
.antMatchers("/actuator/**").permitAll()
// 其他请求全放过
.anyRequest().authenticated()
.and().csrf().disable()
// 开启基本账密校验
.httpBasic();
}
}