版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/FangX_u/article/details/82589727
1.pom.xml:pom文件中引入安全认证依赖
<!-- 安全验证 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.application.yml
#server(eureka 默认端口为:8761)
server:
port: 8761
#spring
spring:
security:
user:
name: user
password: 123456
application:
name: eurekaServerPeer
# eureka
eureka:
client:
register-with-eureka: true # 实例是否在eureka服务器上注册自己的信息以供其他服务发现,默认为true
fetch-registry: false #由于注册中心的职责就是维护服务实例,它并不需要去检索服务, 所以也设置为 false。
service-url:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/
instance:
hostname: localhost
(1)添加:
spring.security.user.name = user
spring.security.password =123456
(2)修改
当自己要注册自己,或者其他服务要在该注册服务中注册时:
1.eureka.client.register-with-eureka = true
2.eureka.client.service-url.defaultZone = http://${spring.security.user.name}:${spring.security.user.password}@
${eureka.instance.hostname}:${server.port}/eureka/
否则报com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server错误
(3)启动后仍然报:
com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known serve:
由于spring boot2.0版的Spring security 会默认开启防csrf攻击,所有的请求都必须携带crsf这个参数,但是从以上的信息来看显然是没有的。所以我们需要主动去关闭,在Eureka服务配置
添加如下类:
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 WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}