在前面的示例中,Eureka Server是允许匿名访问的,在实际项目中,可能希望必须经过用户认证才允许访问Eureka Server。下面来详细探讨Eureka的用户认证。
本小节来构建一个需要登录才能访问的Eureka Server。
1.复制项目microservice-discovery-eureka,将ArtifactId修改为microservice-discovery-eureka-authenticating。
2.在pom.xml中添加spring-boot-starter-security的依赖,该依赖为EurekaServer提供用户认证的能力。
3.在application.yml中添加以下内容:
这样就为Eureka Server添加了基于HTTPbasic的认证。如果不设置这段内容,账号默认是user,密码是一个随机值,该值会在启动时打印出来。
4.将Eureka Server中的eureka.client.serviceUrl.defaultZone修改为http://user:password@EUREKA_HOST:EUREKA_PORT/eureka/的形式。
测试
1.启动microservice-discovery-eureka-authenticating。
2.访问 http://localhost:8761/ 时需要身份验证,如图4-7所示。
图4-7 Eureka Server登录界面
3.输入账号user、密码password123,即可登录并访问Eureka Server。
如何才能将微服务注册到需认证的Eureka Server上呢?答案非常简单,只需将eureka.client.serviceUrl.defaultZone配置为http://user:password@EUREKA_HOST:EUREKA_PORT/eureka/的形式,即可将微服务注册到本例的Eureka Server。
对于更复杂的需求,可创建一个类型为DiscoveryCl ientOptionalArgs的@Bean,并向其中注入ClientFilter,例如: