最近使用SpringCloud在eureka server端添加security登錄認證之后,eureka client注冊啟動一直報錯,大概意思是未發現eureka server,導致注冊啟動失敗!
1 2018-08-09 14:50:06.042 WARN 13256 --- [nfoReplicator-0] c.n.discovery.InstanceInfoReplicator : There was a problem with the instance info replicator 2 3 com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
解決辦法分兩個版本用不同的方式:
- 首先老版本(Spring Cloud 2.0以下):
- 1在application.yml配置中添加如下配置:
security:
basic:
enabled: true # 開啟基於HTTP basic的認證
user:
name: user # 配置登錄的賬號是user
password: password123 #配置登錄的密碼是password123
- 2並在pom.xml中添加如下依賴:
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-security</artifactId> 4 </dependency>
- 新版本(Spring Cloud2.0以上):
- 1 在application.yml添加如下配置:
1 spring: 2 application: 3 name: eureka-server 4 security: 5 user: 6 name: user 7 password: password123
- 2 在pom.xml中添加如下依賴:
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-security</artifactId> 4 </dependency>
- 3 在eureka server啟動類繼承WebSecurityConfigurerAdapter並重寫configure方法從而打開basic這個配置,新版的spring Cloud中basic.enabled是禁用的。
1 security: 2 basic: 3 enabled: true (enabled出現紅波浪線禁用狀態,即失效了) 4 user: 5 name: user 6 password: password123
通過如下代碼即可解決:
1 @SpringBootApplication 2 @EnableEurekaServer 3 public class EurekaApplication extends WebSecurityConfigurerAdapter { 4 public static void main(String[] args) { 5 SpringApplication.run(EurekaApplication.class, args); 6 } 7 8 @Override 9 protected void configure(HttpSecurity http) throws Exception { 10 // Configure HttpSecurity as needed (e.g. enable http basic). 11 http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER); 12 http.csrf().disable(); 13 //注意:為了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 這種方式登錄,所以必須是httpBasic, 14 // 如果是form方式,不能使用url格式登錄 15 http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); 16 17 } 18 }
