Skip to content

1.4 Eureka Authentication

Fanyuepan edited this page Mar 1, 2019 · 1 revision
fly-services-discovery项目中添加引用

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
修改配置文件application.yml,增加以下配置:

spring:
  security:
    user:
      name: panzi
      password: 123456
defaultZone改为http://user:password@host:port/eureka格式

  defaultZone: http://panzi:123456@localhost:${server.port}/eureka

这里需要注意的是,在高版本中,Eureka Client并不能成功注册,会出现401错误.所以还需要在服务端增加配置类:

import org.springframework.context.annotation.Configuration;
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
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭csrf
        http.csrf().ignoringAntMatchers("/eureka/**");
        //开启认证
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}
修改Eureka Client:fly-user-service的配置文件,将defaultZone改为上文中的地址:

defaultZone: http://panzi:123456@localhost:${server.port}/eureka
启动服务端和客户端:访问http://localhost:8761/

img