一、eureka用户认证
之前在注册中心项目的配置文件暴露过eureka的地址
eureka项目的配置文件:
#暴露eureka的服务地址ַ
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
服务调用方,服务提供方项目的配置文件同样配置了eureka的地址,以便启动时进行服务注册与发现,但是存在安全性问题:只要指定eureka的地址,谁都可以访问,因此需要进行认证,连接到 eureka 的时候需要带上连接的用户名和密码
1)引入安全认证相关jar包
<!-- 安全组件包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2)eureka项目配置文件,开启basic校验
security.basic.enabled=true
spring.security.user.name=admin
spring.security.user.password=admin
3)代码配置,在启动类同级目录新建WebSecurityConfigurer类
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//关闭csrf
http.csrf().disable();
//开启认证:URL格式登录必须是httpBasic
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
4)服务注册方、服务调用方也需要修改配置文件,增加用户名、密码
eureka.client.serviceUrl.defaultZone=http://admin:admin@localhost:8763/eureka/
此时,无论通过页面访问