改造我们的 eureka-server,通过集成 Spring-Security 来进行安全认证。

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

添加配置

spring.security.user.name=yinjihuan #用户名
spring.security.user.password=123456 #密码
eureka.client.service-url.defaultZone=http://${spring.security.user.name}:${spring.security.user.password}@localhost:${server.port}/eureka/

添加配置类

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭csrf
        http.csrf().disable();
        // 支持httpBasic
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}

在 Eureka 开启认证后,客户端注册的配置也要加上认证的用户名和密码信息:

eureka.client.serviceUrl.defaultZone=http://zhangsan:123456@localhost:8761/eureka/