SpringCloud之开启Eureka密码认证

突然想起来,一直都是直接注册服务到eureka
在实际开发中,注册中心是有有公网 IP 的,别人都可以把自己的服务注册到我的eureka中
SpringCloud之开启Eureka密码认证_第1张图片
于是了解到可以给eureka设置密码认证。

目录

  • 一、Eureka开启密码认证
    • 1.引入依赖
    • 2. 配置文件
    • 3. 配置类
  • 二、注册服务

一、Eureka开启密码认证

1.引入依赖


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-securityartifactId>
dependency>

2. 配置文件

spring:
  security:
    user:
      name: admin
      password: 123456

3. 配置类

看了网上一堆都是通过继承WebSecurityConfigurerAdapter来实现的。
一试发现这个类在Spring Security 5.7.1及更新版本或者Spring Boot 2.7.0及更新版本已经被弃用了。
SpringCloud之开启Eureka密码认证_第2张图片

Spring Security 5.6.5及更旧版本或Spring Boot 2.6.8

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭csrf
        http.csrf().disable();
        // 支持httpBasic
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}

Spring Security 5.7.1及更新版本或者Spring Boot 2.7.0及更新版本

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        //关闭csrf
        http.csrf().disable();
        //支持httpBasic
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
        return http.build();
    }
}

二、注册服务

修改配置文件,将服务注册到开启了密码认证的eureka中心。

secutiry:
	user:
		name: admin
      	password: 123456

eureka:
  client:
    service-url:
      defaultZone: http://${secutiry.user.name}:${secutiry.user.password}@localhost:8086/eureka

你可能感兴趣的:(SpringCloud,eureka,spring,cloud,java)