Eureka进行安全控制,通过用户名密码来注册到注册中心

首先导入maven依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
</dependency>
然后在配置文件中添加
spring:
  application:
    name: eureka-server
  security:
    user:
      name: admin
      password: 123456
此时启动注册中心就需要输入账号密码登录了
 
修改EurekaClient配置
eureka:
  instance:
    prefer-ip-address: true
  client:
    serviceUrl:
      defaultZone: http://admin:123456@localhost:8761/eureka/
如果不配置用户名和密码,会报401错误
Request execution failure with status code 401; retrying on another server if available
配置上以后还会报错
Request execution failure with status code 403; retrying on another server if available
这是因为Eureka 默认启用了csrf检验,可以将其disable掉
Eureka注册中心添加如下代码:
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 WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        super.configure(http);
    }
}
重启注册中心,就会发现服务注册上来了
但是注册中心日志还会报错
Batch update failure with HTTP status code 401; discarding 1 replication tasks
这是因为在eureka注册中心启用了security安全机制,因此在进行配置defualtZone时也要设置下相关用户名和密码,配置如下:
eureka:
  instance:
    prefer-ip-address: true
  client:
    registerWithEureka: false
    fetchRegistry: false
    server:
      waitTimeInMsWhenSyncEmpty: 0
    service-url:
      defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@localhost:8761/eureka/
注册中心整体配置如下:
原文地址:https://www.cnblogs.com/java-spring/p/13168969.html