spring cloud-给Eureka Server加上安全的用户认证

本文介绍了如何在Eureka服务中配置安全认证,包括pom.xml中引入安全依赖、application.yml的安全配置细节以及解决常见错误的方法。同时,还提供了解决因Spring Security默认开启CSRF保护导致的问题方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
    }
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值