当启用Eureka服务器保护时,Eureka Client无法注册。

当通过 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了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值