栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【SpringCloud】集群下 Eureka 的启动 bug,大坑

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【SpringCloud】集群下 Eureka 的启动 bug,大坑

如题,笔者创建了两个 Eureka Server 做集群,并引入了 Spring Security 在启动这两个 Server 就出现错误,会有各种 bug,比如

There was a problem with the instance info replicator com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server

DiscoveryClient_EUREKA-SERVER/192.168.0.27:8762 - registration failed Cannot execute request on any known server

DiscoveryClient_EUREKA-SERVER/192.168.0.27:8762 - was unable to send heartbeat!

Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://root:123456@localhost:8761/eureka/}

Root name 'timestamp' does not match expected ('instance') for type [simple type, class com.netflix.appinfo.InstanceInfo]

查阅了大量的博客,原因大概是 集群中每个 Eureka Server 会把自己作为客户端 向其他的 Server 注册,当我们引入 Spring Security 的依赖时候,Spring Cloud 2.0 以上会默认启用 csrf 检验,需要在 Eureka Server 端配置Security 的 csrf 检验为 false,否则,会出现其他服务无法注册进 Eureka 注册中心的情况,就是一大堆 bug,我被这个 bug 卡了一天半了!

什么是 csrf:csrf 则通过伪装来自受信任用户的请求来利用受信任的网站

具体的解决办法:在每个 Eureka Server 端新建一个WebSecurityConfigurerAdapter 的继承类,并加上 @EnableWebSecurity 注解。

这里又有两种解决方案,可根据需要具体选择。

方案一:让 CSRF 忽略 /eureka/** 的所有请求

package org.fengluo.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http); // 这句是为了访问 eureka 控制台和 /actuator 时能做安全控制
        http.csrf().ignoringAntMatchers("/eureka/**"); // 忽然 /eureka/** 的所有请求
    }
}

方案二:密码验证依然开启,仅仅关闭 CSRF 的防御机制

package org.fengluo.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 注意:这里如果直接 disable 的话,会把密码验证也关闭了
        http.csrf().disable().authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }
}


即可解决问题!快去试试吧!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/851707.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号