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