上节学习可以启动spring cloud Eureka注册中心服务,这节加上spring.security 的认证功能,加上后,登录Eureka 的网页需要输入账号密码,微服务客户端注册到中心也需要提供账号密码
本节是把上上节学习的 spring boot 和上节学习的 spring cloud Eureka 结合起来,再加上认证功能
一、 spring cloud Eureka server 相关设置
1.pom.xml 加入secirity支持
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. application.properties 设置改为
server.port=8888
eureka.instance.hostname=centos7
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://admin:123@centos7:8888/eureka/
management.endpoints.web.exposure.include=*
spring.security.user.name=admin
spring.security.user.password=123
3. 增加WebSecurityConfig 认证配置类
因为高版本的spring cloud中没有 security.basic.enabled=true这个设置项,这个摸索了好久,最后找到网友的以下这个方案可行。
为了能够接受客户端认证请求,在Eureka server需要增加这个类
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
http.csrf().disable();
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
二、Eureka client 客户端的配置
1.pom.xml 同样加入security支持
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.配置文件 application.properties
server.port=8080
eureka.client.serviceUrl.defaultZone=http://admin:123@centos7:8888/eureka/
spring.application.name=SpringDemo
spring.security.user.name=admin
spring.security.user.password=123
三,测试,分别启动Eureka服务和客户端
1. 需要登录进入Eureka界面
2.输入账号密码后,可见客户端注册成功