SpringCloud 2.x Eureka安全配置

springcloud升级到2.x后Eureka安全配置与1.x有部分变动,具体配置如下:

1、加入依赖:

dependencies {
    implementation('org.springframework.cloud:spring-cloud-starter-netflix-eureka-server')
    testImplementation('org.springframework.boot:spring-boot-starter-test')
    implementation('org.springframework.boot:spring-boot-starter-security')
}

2、配置application.yml,自定义用户名与密码:

server:
  port: 8763
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
spring:
  security:
    user:
      name: admin
      password: abcd1234

3、新版本的security默认开启csrf了,这里我们先关掉它,新建一个配置类:

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

4、浏览器访问,输入刚才设置的用户名与密码:

4、访问成功:

5、客户端访问方式不变。

评论

暂无评论