開啓 Http Basic
現在的實例中,訪問 Eureka Server 是不需要用戶名、密碼的,不需要安全驗證。爲了防止微服務暴露,可以開啓 Http Basic 安全教研。
Eureka Server 開啓 Http Basic
引入 pom 依賴
<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>
創建配置文件
server:
port: 8761
spring:
security:
user:
name: laiyy # 訪問 Eureka Server 的用戶名
password: 123456 # 訪問 Eureka Server 的密碼
eureka:
client:
service-url:
defaultZone: http://localhost:${server.port:8761}/eureka/
register-with-eureka: false
fetch-registry: false
訪問 http://localhost:8761
Eureka Client 開啓 Http Basic
引入 pom 依賴
<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 需要設置爲: http://user:password@ip:port/eureka/
啓動 Eureka Client,驗證 Http Basic
在啓動 Client 後,觀察日誌,可以看到出現了 403 錯誤:
[圖片上傳失敗...(image-6ca959-1551662462133)]
明明已經指定了 Eureka Server 的用戶名、密碼、ip、端口,爲什麼還是註冊失敗?
是因爲 Http Basic 默認是同源的,而 client、server 的 ip、端口不一致,會出現跨域訪問請求,導致 403.
解決辦法:在 Eureka Server 端關閉 csrf 訪問。
@EnableWebSecurity
public class HttpBasicConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.csrf().disable();
}
}
重新啓動 Server、Client,訪問 Server,可以看到 Client 註冊成功