在注冊過程中存在一個風(fēng)險的問題臀规,如果我們的Eureka Server的地址無意暴露在外,那豈不是通過Eureka協(xié)議創(chuàng)建的任意服務(wù)都可以進行注冊到該Eureka Server嗎度液?(當(dāng)然如果你配置了服務(wù)器的安全組并且使用內(nèi)網(wǎng)的IP地址或者主機名方式對外提供服務(wù)注冊地址幾乎不存在這個問題泉手。)
本章目標(biāo)
為Eureka Server穿上安全的外套麸恍,我的注冊中心更安全译仗。
構(gòu)建項目
依然使用idea開發(fā)工具創(chuàng)建一個SpringBoot項目,在依賴的選擇界面我們添加Eureka Server略号、Security相關(guān)依賴刑峡,pom.xml配置文件如下所示:
//...省略部分內(nèi)容
<dependencies>
<!--Eureka服務(wù)端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--添加安全認(rèn)證-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
//...省略部分內(nèi)容
開啟注冊中心安全配置
在添加安全配置之前,我們需要把Eureka Server的配置也一并添加上
配置文件的安全配置
修改application.yml配置文件內(nèi)容玄柠,添加安全配置信息突梦,如下所示:
# 服務(wù)名稱
spring:
# 安全參數(shù)配置
security:
user:
name: api
password: node
roles: SERVICE_NODE
application:
name: hengboy-spring-cloud-eureka
# 服務(wù)端口號
server:
port: 8100
#Eureka 相關(guān)配置
eureka:
client:
service-url:
defaultZone: http://api:node@localhost:${server.port}/eureka/
#defaultZone: http://localhost:8200/eureka/
# 是否從其他的服務(wù)中心同步服務(wù)列表
fetch-registry: true
# 是否把自己作為服務(wù)注冊到其他服務(wù)注冊中心
register-with-eureka: true
# 測試時關(guān)閉自我保護機制,保證不可用服務(wù)及時踢出
enable-self-preservation: false
##剔除失效服務(wù)間隔
eviction-interval-timer-in-ms: 2000
開啟Http Basic 安全認(rèn)證
舊版本的Spring Security的依賴是可以在配置文件內(nèi)容直接通security.basic.enabled參數(shù)進行開啟basic認(rèn)證羽利,不過目前版本已經(jīng)被廢除宫患,既然這種方式不可行,那我們就使用另外一種方式進行配置这弧,通過繼承WebSecurityConfigurerAdapter安全配置類來完成開啟認(rèn)證權(quán)限娃闲,配置類如下所示:
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
/**
* 配置安全信息
* - 禁用csrf攻擊功能
* - 開啟所有請求需要驗證并且使用http basic進行認(rèn)證
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
// 修改前
# 配置Eureka Server 信息
eureka:
client:
service-url:
defaultZone: http://localhost:10000/eureka/
// 修改后
# 配置Eureka Server 信息
eureka:
client:
service-url:
defaultZone: http://api:node@localhost:10000/eureka/
修改后的api:node@這塊的內(nèi)容,前面是spring.security.user.name配置的值匾浪,而后面則是spring.security.user.password配置的值皇帮,@符號后面才是原本之前的Eureka Server的連接字符串信息。
總結(jié)
我們本章為Eureka Server穿上了安全的外套蛋辈,讓它可以更安全属拾,在文章開始的時候我說到了如果使用內(nèi)網(wǎng)IP或者主機名方式進行服務(wù)注冊時是幾乎不存在安全問題的,如果你想你的服務(wù)注冊中心更新安全冷溶,大可不必考慮你的服務(wù)注冊方式都可以添加安全認(rèn)證渐白。