1. 程式人生 > >SpringCloud實戰三:Spring Cloud Eureka 配合 Security 提高安全

SpringCloud實戰三:Spring Cloud Eureka 配合 Security 提高安全

  上篇《SpringCloud實戰二:Spring Cloud Eureka 服務發現與註冊中心》搭建了一個簡單的註冊中心,啟動專案後任何人都可以訪問 http://localhost:10025/ eureka註冊中心,暴露所有註冊的服務IP與埠,雖然 eureka往往隱藏在閘道器後的內網,但也是不安全的
  引入 spring-cloud-starter-security,配置使用者名稱和密碼,訪問註冊中心時只有知道使用者名稱和密碼的使用者才能登入,相對提高了註冊中心的安全性

1.在上篇專案的基礎上,在 eureka-server 專案的 pom.xml 中新增依賴:
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-security</artifactId>
</dependency>

然後在 application.properties 中加入security的使用者名稱和密碼配置:

server.port=10025
eureka.instance.hostname=localhost
eureka.instance.prefer-ip-address=true
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

#配置登入的使用者名稱和密碼
spring.security.user.name=zy
spring.security.user.password=zy123

再新增一個WebSecurityConfig.java類,因為新版的security預設啟用了csrf檢驗,要在eureka-server服務端配置security的csrf檢驗為false,eureka-client才能註冊,而且它還不支援在配置檔案中配置,程式碼如下:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}

此時啟動 eureka-server,再訪問 http://localhost:10025/ ,會發現頁面要你輸入帳號才能登入,使用者名稱和密碼就是上面配置檔案中配置的 zy 123456,輸入後, 進入熟悉的註冊中心
在這裡插入圖片描述

2.此時再啟動 eureka-client ,會發現控制檯已經輸出了一些錯誤資訊,提示未發現server,明明是 localhost:10025,怎麼會找不到,因為 eureka-server 配置了進入的帳號和密碼,因此 eureka-client 向 eureka-server 註冊時,也要攜帶 帳號和密碼才能註冊

在這裡插入圖片描述

修改eureka-client 的application.properties配置檔案,配置如下:

server.port=9600
spring.application.name=eureka-client
eureka.instance.prefer-ip-address=true

#配置eureka-server security的賬戶資訊
eureka.client.serviceUrl.defaultZone=http://zy:[email protected]:10025/eureka/

再啟動 eureka-client,重新整理註冊中心 http://localhost:10025,看到 eureka-client 正常註冊到註冊中心了
在這裡插入圖片描述

好了,本篇主要是給 eureka 註冊中心設定個登入帳號,指定帳號才能登入,提高安全性