突然想起来,一直都是直接注册服务到eureka
在实际开发中,注册中心是有有公网 IP 的,别人都可以把自己的服务注册到我的eureka中

于是了解到可以给eureka设置密码认证。
<!--引入security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
spring:
security:
user:
name: admin
password: 123456
看了网上一堆都是通过继承WebSecurityConfigurerAdapter来实现的。
一试发现这个类在Spring Security 5.7.1及更新版本或者Spring Boot 2.7.0及更新版本已经被弃用了。

Spring Security 5.6.5及更旧版本或Spring Boot 2.6.8
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
// 关闭csrf
http.csrf().disable();
// 支持httpBasic
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
Spring Security 5.7.1及更新版本或者Spring Boot 2.7.0及更新版本
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//关闭csrf
http.csrf().disable();
//支持httpBasic
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
return http.build();
}
}
修改配置文件,将服务注册到开启了密码认证的eureka中心。
secutiry:
user:
name: admin
password: 123456
eureka:
client:
service-url:
defaultZone: http://${secutiry.user.name}:${secutiry.user.password}@localhost:8086/eureka