com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server——security未关闭csrf检验

前言

eureka服务开启security认证后, 微服务客户端启动报如题错误, 新版(Spring Cloud 2.0 以上)的security默认启用了csrf检验,要在eurekaServer端配置security的csrf检验为false

解决方法

  1. 添加一个继承 WebSecurityConfigurerAdapter 的类;
  2. 在类上添加 @EnableWebSecurity 注解;
  3. 覆盖父类的 configure(HttpSecurity http) 方法,关闭掉 csrf

示例代码

package com.xgcd.cloudeureka.config;

import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();// 关闭csrf校验
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();// 开启认证
//        super.configure(http);// 需要注释,否则Caused by: java.lang.IllegalStateException: Can't configure anyRequest after itself
    }
}

重启eureka客户端,成功。

访问http:localhost:8761

客户端注册成功

感谢

https://blog.csdn.net/makyan/article/details/88594227

原文地址:https://www.cnblogs.com/yadongliang/p/13737464.html