首先导入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
此时启动注册中心就需要输入账号密码登录了
![](https://img2020.cnblogs.com/blog/1034738/202006/1034738-20200620154724757-831561688.png)
修改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
![](https://img2020.cnblogs.com/blog/1034738/202006/1034738-20200620154851159-1059829942.png)
配置上以后还会报错
Request execution failure with status code 403; retrying on another server if available
![](https://img2020.cnblogs.com/blog/1034738/202006/1034738-20200620154911746-814357673.png)
这是因为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); } }
重启注册中心,就会发现服务注册上来了
![](https://img2020.cnblogs.com/blog/1034738/202006/1034738-20200620155009383-2017026165.png)
但是注册中心日志还会报错
Batch update failure with HTTP status code 401; discarding 1 replication tasks
![](https://img2020.cnblogs.com/blog/1034738/202006/1034738-20200620155027636-1733815960.png)
这是因为在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://img2020.cnblogs.com/blog/1034738/202006/1034738-20200620155115134-1196039502.png)