spring-cloud eureka (2.x版本) 开启密码认证 (不同于1.x)

一、导语

前段时间升级了spring-cloud版本,至于为什么要升级,主要是那个躁动的心~~,毕竟是自己的项目,自然想用最新版本。这也就有了今天这个2.x版的eureka 开启密码认证。

二、eureka模块修改

1、在eureka的pom文件中加入下面的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2、在application配置文件中加入密码设置(yum类型的配置文件自行百度即可,这里演示application)(ps:这里的需要加上spring前缀,和1.x的配置不同这里不对比了)

spring.security.basic.enabled=true
           spring.security.user.name=admin
           spring.security.user.password=admin

3、 重写WebSecurityConfigurerAdapter的configure方法,因为 Spring Security 默认开启了所有 CSRF 攻击防御,需要禁用 /eureka 的防御。

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;

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 开启认证
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
        http.csrf().ignoringAntMatchers("/eureka/**");
        super.configure(http);
    }

}

4、至此,eureka服务的配置完成,输入eureka地址登陆即可看到监控页面。

三、其它模块注册到eureka修改

1、只需要修改注册到eureka的地址即可格式如下

           eureka.client.serviceUrl.defaultZone=http://用户名:密码@localhost:8080/eureka

           举个栗子:eureka.client.serviceUrl.defaultZone=http://admin:admin@localhost:8080/eureka

猜你喜欢

转载自blog.csdn.net/qq_37054881/article/details/86608151