Eureka 自帶了一個 Web 的管理頁面,方便我們查詢註冊到上面的實例信息,但是有一個問題:如果在實際使用中,註冊中心地址有公網 IP 的話,必然能直接訪問到,這樣是不安全的。所以我們需要對 Eureka 進行改造,加上權限認證來保證安全性。
改造我們的 eureka-server,通過集成 Spring-Security 來進行安全認證。
在 pom.xml 中添加 Spring-Security 的依賴包,代碼如下所示。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
然後在 application.properties 中加上認證的配置信息:
spring.security.user.name=yinjihuan #用戶名
spring.security.user.password=123456 #密碼
增加 Security 配置類:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 關閉csrf
http.csrf().disable();
// 支持httpBasic
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
重新啓動註冊中心,訪問 http://localhost:8761/,此時瀏覽器會提示你輸入用戶名和密碼,輸入正確後才能繼續訪問 Eureka 提供的管理頁面。
在 Eureka 開啓認證後,客戶端註冊的配置也要加上認證的用戶名和密碼信息:
eureka.client.serviceUrl.defaultZone=http://zhangsan:123456@localhost:8761/eureka/