Spring Cloud 如何保證微服務(wù)內(nèi)安全
在微服務(wù)的架構(gòu)下,我們需要把系統(tǒng)的業(yè)務(wù)劃分成多個單一的微服務(wù)。每個微服務(wù)都會提供接口供其他微服務(wù)調(diào)用,在Dubbo中可以通過rmi、nio等實現(xiàn),Spring Cloud中是通過http調(diào)用的。
但有些時候,我們只希望用戶通過我們的網(wǎng)關(guān)調(diào)用微服務(wù),不允許用戶直接請求微服務(wù)。這時我們就可以借助Spring Security來保障安全。
二、使用步驟2.1 在提供接口的微服務(wù)項目中配置Spring Security1 首先在pom.xml引入Spring Security的相關(guān)配置,如下
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>
2 在qpplication.yml中配置賬號密碼,如下
security: basic: enabled: true user: name: sunbufu password: 123456
3 此時訪問接口發(fā)現(xiàn)已經(jīng)需要認證了。
輸入正確的賬號和密碼后就可以訪問了。
2.2在調(diào)用微服務(wù)項目中配置Feign的賬號密碼1 在application.yml中配置賬號密碼
security: user: name: sunbufu password: 123456
2 添加Feign的配置文件
package com.sunbufu.config;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import feign.auth.BasicAuthRequestInterceptor;@Configurationpublic class FeignConfiguration { @Value('${security.user.name}') private String userName; @Value('${security.user.password}') private String passWord; @Bean public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){return new BasicAuthRequestInterceptor(userName, passWord); }}
3 這樣完成后,就可以正常的訪問了。
git源碼地址:https://github.com/sunbufu/sunbufu-cloud
下面是這4個工程的說明:1. sunbufu-erueka:Eureka服務(wù)的工程
2. sunbufu-hello-face:服務(wù)接口的定義工程,其中包括定義微服務(wù)需要實現(xiàn)什么功能,其他微服務(wù)怎么調(diào)用,以及feign的配置
3. sunbufu-hello-impl:服務(wù)接口的實現(xiàn)工程,實現(xiàn)了sunbufu-hello-face定義的功能
4. sunbufu-hello-web:服務(wù)的網(wǎng)關(guān)工程,主要為了調(diào)用sunbufu-hello-face
Spring Cloud服務(wù)安全連接Spring Cloud可以增加HTTP Basic認證來增加服務(wù)連接的安全性。
1、加入security啟動器在maven配置文件中加入Spring Boot的security啟動器。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>
這樣,就開啟對服務(wù)連接的安全保護,系統(tǒng)默認為生成一個用戶名為”user”及一個隨機密碼,隨機密碼在服務(wù)啟動的時候在日志中會打印出來。
2、自定義用戶名密碼隨機密碼沒什么實際意義,我們需要一個固定的連接用戶名和密碼。
在應(yīng)用配置文件中加入以下配置即可。
security: user: name: admin password: admin123456
這樣配置完后在連接這個服務(wù)的時候就會要求輸入用戶名和密碼,如果認證失敗會返回401錯誤。
{ 'timestamp': 1502689874556, 'status': 401, 'error': 'Unauthorized', 'message': 'Bad credentials', 'path': '/test/save'}3、安全連接
1、注冊中心安全連接
username:password@ipaddress
2、Feign申明式服務(wù)安全連接
@FeignClient(name = 'SERVICE', configuration = FeignAuthConfig.class)public interface OrderService extends OrderAPI {}
@Configurationpublic class FeignAuthConfig { @Bean public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {return new BasicAuthRequestInterceptor('admin','admin123456'); }}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
