SpringBoot Admin使用Nacos作为服务注册中心
    
  
      
      
     
    
      
        之前我们都讲了普通的服务使用SBD,如果我们使用的是类似Nacos、Eureka、Consul等注册中心实现服务注册的,那我们应该怎么配置相应的安全策略?
在Client端,我们依然需要引入sbd-client相关依赖包:
1 2 3 4
   | <dependency>   <groupId>de.codecentric</groupId>   <artifactId>spring-boot-admin-starter-client</artifactId> </dependency>
   | 
 
即使是使用注册中心,该依赖的包也不能少,不然client就走丢了
包引入之后,同样的是在项目配置文件中将actuator的相关端口暴露出来,这个之前讲过,包括Spring Security的配置,就不在赘述了,贴一下配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
   | management:   endpoints:     web:       exposure:         include: '*'   endpoint:     health:       show-details: ALWAYS
  spring: 	boot: 		admin: 			client: 				url: <sbd server url> 				instance: 				   				  service-base-url: http://host_ip:host_port 					metadata: 						user.name: ${spring.security.user.name} 						user.password: ${spring.security.user.password} 	 	security: 		user: 			name: <actuator user> 			password: <password for actuator user>
   | 
 
Spring Security配置:
1 2 3 4 5 6 7 8 9 10 11 12
   | import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {
      @Override     protected void configure(HttpSecurity http) throws Exception {        http.httpBasic().and().authorizeRequests().antMatchers("/actuator/**").authenticated().anyRequest().permitAll();     } }
   | 
 
client端已经配置完了,接下来就是SBD server端的配置了,和我们之前的配置也没差太多,主要是将SBD的用户名密码告知注册中心,我们这里使用的是Nacos,所以我们要将账号信息告诉Nacos,配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
   | spring:   application:     name: jsb_micro_admin_server   security:     user:       name: <sbd user>       password: <password for sbd user>   cloud:     nacos:       discovery:         server-addr: <nacos_server_ip>:<nacos_server_port>         namespace: prd         ip: <sbd_ip>         metadata:           user.name: ${spring.security.user.name}           user.password: ${spring.security.user.password}
   | 
 
双方服务启动即可,注意这里的namespace需要与服务的namespace一致,也就是它只能发现同一个namespace下的服务。
至此所有的配置就都搞定了,启动即可