開(kāi)啟 Http Basic
現(xiàn)在的實(shí)例中,訪(fǎng)問(wèn) Eureka Server 是不需要用戶(hù)名海蔽、密碼的锥咸,不需要安全驗(yàn)證。為了防止微服務(wù)暴露柬采,可以開(kāi)啟 Http Basic 安全教研欢唾。
Eureka Server 開(kāi)啟 Http Basic
引入 pom 依賴(lài)
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
創(chuàng)建配置文件
server:
port: 8761
spring:
security:
user:
name: laiyy # 訪(fǎng)問(wèn) Eureka Server 的用戶(hù)名
password: 123456 # 訪(fǎng)問(wèn) Eureka Server 的密碼
eureka:
client:
service-url:
defaultZone: http://localhost:${server.port:8761}/eureka/
register-with-eureka: false
fetch-registry: false
訪(fǎng)問(wèn) http://localhost:8761
Eureka Client 開(kāi)啟 Http Basic
引入 pom 依賴(lài)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置文件
spring:
application:
name: spring-cloud-eureka-client-http-basic
eureka:
client:
security:
basic:
user: laiyy
password: 123456
service-url:
defaultZone: http://${eureka.client.security.basic.user}:${eureka.client.security.basic.password}@localhost:8761/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${server.port}
server:
port: 8081
需要注意,defaultZone 需要設(shè)置為: http://user:password@ip:port/eureka/
啟動(dòng) Eureka Client粉捻,驗(yàn)證 Http Basic
在啟動(dòng) Client 后礁遣,觀察日志,可以看到出現(xiàn)了 403 錯(cuò)誤:
[圖片上傳失敗...(image-6ca959-1551662462133)]
明明已經(jīng)指定了 Eureka Server 的用戶(hù)名肩刃、密碼祟霍、ip、端口盈包,為什么還是注冊(cè)失敺心拧?
是因?yàn)?Http Basic 默認(rèn)是同源的呢燥,而 client崭添、server 的 ip、端口不一致疮茄,會(huì)出現(xiàn)跨域訪(fǎng)問(wèn)請(qǐng)求滥朱,導(dǎo)致 403.
解決辦法:在 Eureka Server 端關(guān)閉 csrf 訪(fǎng)問(wèn)。
@EnableWebSecurity
public class HttpBasicConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.csrf().disable();
}
}
重新啟動(dòng) Server力试、Client徙邻,訪(fǎng)問(wèn) Server,可以看到 Client 注冊(cè)成功