當咱們直接配置完SpringCloudEureka的時候,任何人直接就能夠訪問,這樣是極不安全的!!外網的狀況下是絕對不容許的!
好在有提供瞭解決方案,下面拿爲咱們提供的Security解決web
SpringCloud版本:
<spring-cloud.version>Greenwich.SR4</spring-cloud.version>
註冊中心
一、pom文件添加security座標
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>二、在application.yml文件中添加配置(properties同樣,格式稍微變化);若是是集羣的話,全部集羣配置文件都要修改以下格式
spring: security: #開啓安全驗證 user: name: root #用戶名 password: admin #密碼
三、註冊地址變爲以下格式(service-url.defaultZone);若是是集羣的話,全部集羣配置文件都要修改以下格式
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@IP:${server.port}/eureka/ #eureka註冊中心地址四、添加一個SpringSecurity配置類
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http);//加這句是爲了訪問eureka控制檯和/actuator時能作安全控制 http.csrf().disable();//關閉csrf } }註冊中心完成!看到以下效果即成功
客戶端
一、修改application.yml配置文件(service-url.defaultZone) 便可
eureka: client: service-url: defaultZone: http://註冊中心配置的用戶名:註冊中心配置的密碼@eureka1:端口/eureka/
下面是個人註冊中心配置(集羣版,數量爲2)
application.eureka1.ymlspring
spring: application: name: eureka-server security: #開啓安全驗證 user: name: root password: admin server: port: 8761 eureka: instance: hostname: eureka1 #設置eureka實例名,與配置文件的變量爲主 client: service-url: defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka2:${server.port}/eureka/ #eureka註冊中心地址 # server: # enable-self-preservation: false #關閉自我保護:true開啓,false關閉 默認爲true # eviction-interval-timer-in-ms: 10000 #掃描清理間隔時間(單位:毫秒 默認是60*1000)
application.eureka2.yml安全
spring: application: name: eureka-server security: #開啓安全驗證 user: name: root password: admin server: port: 8761 eureka: instance: hostname: eureka2 #設置eureka實例名,與配置文件的變量爲主 client: service-url: defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka1:${server.port}/eureka/ #eureka註冊中心地址 #server: ## enable-self-preservation: false #關閉自我保護:true開啓 false關閉 默認true ## eviction-interval-timer-in-ms: 10000 #清理間隔時間(單位:毫秒 默認60*1000)
客戶端配置服務器
spring: application: name: eureka-provider server: port: 9090 eureka: client: service-url: defaultZone: http://root:admin@eureka1:8761/eureka/,http://root:admin@eureka2:8761/eureka/ #設置服務註冊中心地址,多個之間用","分割 instance: lease-renewal-interval-in-seconds: 1 #每隔1s發送一次心跳,證實本身還活着 lease-expiration-duration-in-seconds: 2 #告訴服務器若是2s沒有發送心跳,就表明死了,將我剔除掉 management: endpoints: web: exposure: include: shutdown #暴漏shutdown端點服務 endpoint: shutdown: enabled: true