学习Spring Cloud中eureka注册中心添加security认证,eureka client注册启动报错

最近使用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. 1在application.yml配置中添加如下配置:
security:
  basic:
    enabled: true # 开启基于HTTP basic的认证
  user:
    name: user  # 配置登录的账号是user
    password: password123 #配置登录的密码是password123
  1. 2并在pom.xml中添加如下依赖:
1 <dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-security</artifactId>
4 </dependency>
  • 新版本(Spring Cloud2.0以上):
  1. 1 在application.yml添加如下配置:
1 spring:
2   application:
3     name: eureka-server
4   security:
5     user:
6       name: user
7       password: password123
  1. 2 在pom.xml中添加如下依赖:
1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-security</artifactId>
4 </dependency>
  1. 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 }

 

posted @ 2019-06-26 00:58  MrAshin  阅读(1997)  评论(1编辑  收藏  举报