玩轉SpringCloud專題(八)-SpringCloud註冊中心Eureka安全認證

1.項目結構

在SpringCloud服務中爲了提高註冊中心的安全性我們可以整合springsecurity來實現完全認證。
在這裏插入圖片描述

Eureka服務中心做的高可用的配置
provide提供服務,需要到註冊中心註冊(需要認證)
consumer服務消費者,需要從註冊中心中發現服務,同樣需要認證

2.服務註冊中心配置

2.1.添加Spring Security依賴

因爲是在SpringBoot項目中,所以添加了Security的依賴會幫助我們完成自動配置。非常方便

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2.2.修改配置文件

設置特定的賬號密碼,放開安全認證

#開啓 http basic 的安全認證
security.basic.enabled=true
security.user.name=bruceliu
security.user.password=123456

註冊中心相互之間也需要認證,設置賬號密碼

defaultZone: http://bruceliu:123456@eureka7002.com:7002/eureka,http://bruceliu:123456@eureka7003.com:7003/eureka

或者引用變量:

defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka7002.com:7002/eureka,http://${spring.security.user.name}:${spring.security.user.password}@eureka7003.com:7003/eureka

2.3.註冊中心關閉Spring Security的CSRF驗證

package com.bruceliu;


import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @BelongsProject: springcloud0310
 * @BelongsPackage: com.bruceliu
 * @Author: bruceliu
 * @QQ:1241488705
 * @CreateTime: 2020-03-10 19:48
 * @Description: TODO
 */

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.csrf().disable(); // 關閉csrf
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); // 開啓認證
    }
}

如果不關閉,那麼客戶端就連接不上.

2.部署啓動

重新將項目打包部署,然後訪問註冊中心,會提示輸入賬號密碼
在這裏插入圖片描述
輸入: bruceliu123456 就能進入了。
在這裏插入圖片描述

3.服務提供者配置

3.1.修改配置文件

因爲現在註冊中心需要認證,所以我們在註冊的地址後需要添加對應的賬號信息,如下:

defaultZone: http://bruceliu:123456@eureka7002.com:7002/eureka,http://bruceliu:123456@eureka7003.com:7003/eureka

3.2.啓動程序

啓動程序,註冊並提供服務,觀察註冊中心
在這裏插入圖片描述

4.消費者配置

4.1.修改配置文件

因爲現在註冊中心需要認證,所以我們在註冊的地址後需要添加對應的賬號信息,如下:

defaultZone: http://bruceliu:123456@eureka7002.com:7002/eureka,http://bruceliu:123456@eureka7003.com:7003/eureka

在這裏插入圖片描述

5.測試調用

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章