当通过 spring-boot-starter-security
将Spring Security添加到 Eureka 服务器的类路径中时,即可保护Eureka服务器。
此时启用Eureka Client 发现无法向Eureka Server注册。
具体异常:
com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
···
查看Spring Cloud文档中的 Securing The Eureka Server,按其中说明
By default when Spring Security is on the classpath it will require that a valid CSRF token be sent with every request to the app. Eureka clients will not generally possess a valid cross site request forgery (CSRF) token you will need to disable this requirement for the /eureka/** endpoints.
翻译如下:
默认情况下,当Spring Security在类路径上时,它将要求在每次向应用程序发送请求时都发送有效的CSRF令牌。Eureka客户通常不会拥有有效的跨站点请求伪造(CSRF)令牌,您需要为/eureka/**端点禁用此要求。
在启动类中添加以下配置(或者你可以单独写一个@Configuration
bean):
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/eureka/**");
super.configure(http);
}
}
此时发现依旧报上面的异常。
我们知道当加入Spring Security依赖的时候,项目会有一个默认的用户 name :user,然后每次启动随机生成一个 password。我想是不是这个的原因,因为每次启动都随机密码,无法配置,所以在 application.yml
中添加了如下配置:
spring:
security:
user:
name: admin
password: pwd
然后按Spring Cloud文档 Authenticating with the Eureka Server【通过Eureka Server身份验证】中描述的:
HTTP basic authentication is automatically added to your eureka client if one of the
eureka.client.serviceUrl.defaultZone
URLs has credentials embedded in it (curl style, as follows: user:password@localhost:8761/eureka).
翻译如下:
如果其中一个eureka.client.serviceUrl.defaultZone
URL内嵌了凭据,则HTTP基本身份验证会自动添加到您的eureka客户端(卷曲样式,如下:http://user:password@localhost:8761/eureka
)。
将 Eureka Client 的这个配置修改为:
eureka:
client:
serviceUrl:
defaultZone: http://admin:pwd@localhost:8761/eureka/
此时Eureka Client就可以成功注册到Eureka Server了。