成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

SpringCloud微服務(wù),如何保證對外接口的安全?

開發(fā) 架構(gòu)
在本文中,我們深入研究了微服務(wù)架構(gòu)中對外開放接口的安全性保障機制。我們著重關(guān)注了那些暴露在外網(wǎng)的API接口面臨的兩個關(guān)鍵安全問題:篡改和重放。

大家好,我是飄渺。如果你的微服務(wù)需要向第三方開放接口,如何確保你提供的接口是安全的呢?

1. 什么是安全接口

通常來說,要將暴露在外網(wǎng)的 API 接口視為安全接口,需要實現(xiàn)防篡改和防重放的功能。

1.1 什么是篡改問題?

由于 HTTP 是一種無狀態(tài)協(xié)議,服務(wù)端無法確定客戶端發(fā)送的請求是否合法,也不了解請求中的參數(shù)是否正確。以一個充值接口為例:

http://localhost/api/user/recharge?user_id=1001&amount=10

如果非法用戶通過抓包獲取接口參數(shù)并修改 user_id 或 amount 的值,就能為任意賬戶添加余額。

1.1.1 如何解決篡改問題?

雖然使用 HTTPS 協(xié)議能對傳輸?shù)拿魑倪M行加密,但黑客仍可截獲數(shù)據(jù)包進行重放攻擊。兩種通用解決方案是:

  1. 使用 HTTPS 加密接口數(shù)據(jù)傳輸,即使被黑客破解,也需要耗費大量時間和精力。
  2. 在接口后臺對請求參數(shù)進行簽名驗證,以防止黑客篡改。

簽名的實現(xiàn)過程如下圖所示:

圖片圖片

  • 步驟1:客戶端使用約定好的規(guī)則對傳輸?shù)膮?shù)進行加密,得到簽名值sign1,并且將簽名值也放入請求的參數(shù)中,隨請求發(fā)送至服務(wù)端。
  • 步驟2:服務(wù)端接收到請求后,使用約定好的規(guī)則對請求的參數(shù)再次進行簽名,得到簽名值 sign2。
  • 步驟3:服務(wù)端比對 sign1 和 sign2 的值,若不一致,則認定為被篡改,判定為非法請求。

1.2. 什么是重放問題?

防重放也叫防復用。簡單來說就是我獲取到這個請求的信息之后什么也不改,,直接拿著接口的參數(shù)去 重復請求這個充值的接口。此時我的請求是合法的, 因為所有參數(shù)都是跟合法請求一模一樣的。重放攻擊會造成兩種后果:

  1. 針對插入數(shù)據(jù)庫接口:重放攻擊,會出現(xiàn)大量重復數(shù)據(jù),甚至垃圾數(shù)據(jù)會把數(shù)據(jù)庫撐爆。
  2. 針對查詢的接口:黑客一般是重點攻擊慢查詢接口,例如一個慢查詢接口1s,只要黑客發(fā)起重放攻擊,就必然造成系統(tǒng)被拖垮,數(shù)據(jù)庫查詢被阻塞死。

1.2.1 如何解決重放問題?

防重放,業(yè)界通?;?nonce + timestamp 方案實現(xiàn)。每次請求接口時生成 timestamp 和 nonce 兩個額外參數(shù),其中 timestamp 代表當前請求時間,nonce 代表僅一次有效的隨機字符串。生成這兩個字段后,與其他參數(shù)一起進行簽名,并發(fā)送至服務(wù)端。服務(wù)端接收請求后,先比較 timestamp 是否超過規(guī)定時間(如60秒),再查看 Redis 中是否存在 nonce,最后校驗簽名是否一致,是否有篡改。

如果看過我DDD&微服務(wù)系列中冪等方案的文章,對于nonce方案肯定比較熟悉,這就是冪等方案中的token機制,只不過此時冪等key是由客戶端生成的。

圖片圖片

2. 身份認證方案

我們已經(jīng)了解了如何解決對外接口可能遇到的篡改和重放問題,但還遺漏了最關(guān)鍵的身份認證環(huán)節(jié)。一般而言,對互聯(lián)網(wǎng)開放的接口不是任何人都能調(diào)用的,只有經(jīng)過認證的用戶或機構(gòu)才有權(quán)限訪問。解決身份認證問題通常通過 AppId 和 AppSecret 實現(xiàn)。

2.1 AppId + AppSecret

AppId作為一種全局唯一的標識符,主要用于用戶身份識別。為防止其他用戶惡意使用別人的 AppId 發(fā)起請求,通常采用配對 AppSecret 的方式,類似一種密碼。在請求方發(fā)起請求時,需將 AppID 和 AppSecret 搭配上前文提到的安全方案,一并簽名提交給提供方驗證。

現(xiàn)在,讓我們再來梳理一下完整的簽名方案。

1、服務(wù)方提供一組 AppId 和 AppSecret,并由客戶端保存。

2、將timestamp、nonce、AppId 與請求參數(shù)一起并按照字典排序,使用URL鍵值對(key1=value1&key2=value2…)的格式拼接形成字符串StringA。

3、在StringA的最后拼接上AppSecret,得到字符串StringB。

4、使用摘要算法對 StringB 進行加密,并將得到的字符串轉(zhuǎn)為大寫,得到簽名值 sign,將其與參數(shù)一起發(fā)送給服務(wù)端。

5、服務(wù)端接收請求后,對接口進行校驗(時間、隨機字符串、身份驗證、簽名)。

在這個流程中,AppID 參與本地加密和網(wǎng)絡(luò)傳輸,而 AppSecret 僅作本地加密使用,不參與網(wǎng)絡(luò)傳輸。服務(wù)端拿到 AppID 后,從存儲介質(zhì)中獲取對應(yīng)的 AppSecret,然后采用與客戶端相同的簽名規(guī)則生成服務(wù)端簽名,最后比較客戶端簽名和服務(wù)端簽名是否一致。

3. 代碼實現(xiàn)

"Talk is cheap. Show me the code." 說了這么久,現(xiàn)在讓我們從代碼的角度來看看如何在 DailyMart 中將上面的理論知識串聯(lián)起來,安全地對外提供接口。

本文涉及到的所有代碼都已上傳至github,如果需要請參考文末方式進行獲取。

3.1 AppId 和 AppSecret的生成

在生成 AppId 和 AppSecret 時,只需確保 AppId 的全局唯一性,然后將生成的 AppId 和 AppSecret 進行綁定。在 DailyMart 中,我們使用短鏈的生成算法來生成 AppId,再對 AppId 進行 SHA 加密后得到對應(yīng)的 AppSecret。

private static String getAppKey() {
 long num = IdUtils.nextId();
 StringBuilder sb = new StringBuilder();
 do {
  int remainder = (int) (num % 62);
  sb.insert(0, BASE62_CHARACTERS.charAt(remainder));
  num /= 62;
 } while (num != 0);
 return sb.toString();
}

通過這個算法生成的 AppId 和 AppSecret 形如:

appKey=6iYWoL2hBk9, appSecret=5de8bc4d8278ed4f14a3490c0bdd5cbe369e8ec9

3.2 API校驗器

在一個系統(tǒng)中可能存在多種認證邏輯,比如既要支持今天所講的開放接口校驗邏輯,還需要支持內(nèi)部服務(wù)的 JWT 認證邏輯。為了方便處理,我們抽象一個 API 認證接口,各種認證邏輯獨立到自己的實現(xiàn)中,對于今天所講的開放接口認證,主要關(guān)注 ProtectedApiAuthenticator。

圖片圖片

//認證接口
public interface ApiAuthenticator {
  AuthenticatorResult auth(ServerWebExchange request); 
}

//具體實現(xiàn)
@Slf4j
public class ProtectedApiAuthenticator implements ApiAuthenticator {
  ...
}

3.2 網(wǎng)關(guān)過濾器

接口的安全校驗很適合放在網(wǎng)關(guān)層實現(xiàn),因此我們需要在網(wǎng)關(guān)服務(wù)中創(chuàng)建一個過濾器 ApiAuthenticatorFilter。

@Component
@Slf4j
public class ApiAuthenticatorFilter implements GlobalFilter, Ordered {
    ...
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       
        // 獲取認證邏輯
        ApiAuthenticator apiAuthenticator = getApiAuthenticator(rawPath);
        AuthenticatorResult authenticatorResult = apiAuthenticator.auth(exchange);
      
        if (!authenticatorResult.isResult()) {
            return Mono.error(new HttpServerErrorException(
                    HttpStatus.METHOD_NOT_ALLOWED, authenticatorResult.getMessage()));
        }
        
        return chain.filter(exchange);
        
    }
    
   
   /**
     * 確定認證策略
     * @param rawPath 請求路徑
     */
    private ApiAuthenticator getApiAuthenticator(String rawPath) {
        String[] parts = rawPath.split("/");
        if (parts.length >= 4) {
            String parameter = parts[3];
              return switch (parameter) {
                case PROTECT_PATH ->   new ProtectedApiAuthenticator();
                case PRIVATE_PATH ->   new PrivateApiAuthenticator();
                case PUBLIC_PATH ->    new PublicApiAuthenticator();
                case DEFAULT_PATH ->   new DefaultApiAuthenticator();
                default -> throw new IllegalStateException("Unexpected value: " + parameter);
              };
        }
        return new DefaultApiAuthenticator();
    }
    
}

上面提到過,不同類型的服務(wù)其接口認證不一樣,為了便于區(qū)分,可以規(guī)定對于外部請求都增加一個特定的請求前綴 /pt/,如 apigw.xxx.com/order-service/api/pt/creadeOrder。這樣在過濾器內(nèi)部就需要通過 getApiAuthenticator() 方法確定認證邏輯。

3.3 接口安全認證

正如上文所說,服務(wù)端獲取到請求參數(shù)以后需要檢查請求時間是否過期,nonce是否已經(jīng)被使用,簽名是否正確。

圖片圖片

按照這個邏輯我們很容易在ProtectedApiAuthenticator認證器中寫出這樣的代碼。

@Slf4j
public class ProtectedApiAuthenticator implements ApiAuthenticator {

    @Override
    public AuthenticatorResult auth(ServerWebExchange exchange)  {
        
        // 1. 校驗參數(shù)
        boolean checked = preAuthenticationCheck(requestHeader);
        if (!checked) {
            return new AuthenticatorResult(false, "請攜帶正確參數(shù)訪問");
        }

        // 2 . 重放校驗
        // 判斷timestamp時間戳與當前時間是否操過60s(過期時間根據(jù)業(yè)務(wù)情況設(shè)置),如果超過了就提示簽名過期。
        long now = System.currentTimeMillis() ;      
         if (now - Long.parseLong(requestHeader.getTimestamp()) > 60000) {
            return new AuthenticatorResult(false, "請求超時,請重新訪問");
         }

        // 3. 判斷nonce
        boolean nonceExists = distributedCache.hasKey(NONCE_KEY + requestHeader.getNonce());
        if (nonceExists) {
            return new AuthenticatorResult(false, "請勿重復提交請求");
        } else {
            distributedCache.put(NONCE_KEY + requestHeader.getNonce(), requestHeader.getNonce(), 60000);
        }
      
        // 4. 簽名校驗
       SortedMap<String, Object> requestBody = CachedRequestUtil.resolveFromBody(exchange);
       String sign = buildSign(requestHeader,requestBody);
      if(!sign.equals(requestHeader.getSign())){
        return new AuthenticatorResult(false, "簽名錯誤");
      }
      
      return new AuthenticatorResult(true, "");
}

這樣的寫法雖然能夠完成校驗邏輯,但稍顯不夠優(yōu)雅。在這種場景中,使用設(shè)計模式中的責任鏈模式是非常合適的選擇。通過責任鏈模式,將校驗邏輯分解為多個責任鏈節(jié)點,每個節(jié)點專注于一個方面的校驗,使得代碼更加清晰和易于維護。

責任鏈模式已經(jīng)在我星球設(shè)計模式專欄中有詳細介紹與說明,這里就不再贅述了~

@Slf4j
public class ProtectedApiAuthenticator implements ApiAuthenticator {

    @Override
    public AuthenticatorResult auth(ServerWebExchange exchange)  {
        ...
        //構(gòu)建校驗對象
        ProtectedRequest protectedRequest = ProtectedRequest.builder()
                .requestHeader(requestHeader)
                .requestBody(requestBody)
                .build();

    //責任鏈上下文
        SecurityVerificationChain securityVerificationChain = SpringBeanUtils.getInstance().getBean(SecurityVerificationChain.class);

        return securityVerificationChain.handler(protectedRequest);

    }

}

3.4 基于責任鏈的認證實現(xiàn)

圖片圖片

3.4.1 創(chuàng)建責任鏈的認證接口

public interface SecurityVerificationHandler extends Ordered {
    /**
     * 請求校驗
     */
    AuthenticatorResult handler(ProtectedRequest protectedRequest);
}

3.4.2 實現(xiàn)參數(shù)校驗邏輯

@Component
public class RequestParamVerificationHandler implements SecurityVerificationHandler {

    @Override
    public AuthenticatorResult handler(ProtectedRequest protectedRequest) {

        boolean checked = checkedHeader(protectedRequest.getRequestHeader());

        if(!checked){
            return new AuthenticatorResult(false,"請攜帶正確的請求參數(shù)");
        }
        return new AuthenticatorResult(true,"");
    }

    private boolean checkedHeader(RequestHeader requestHeader) {
        return Objects.nonNull(requestHeader.getAppId()) &&
                Objects.nonNull(requestHeader.getSign()) &&
                Objects.nonNull(requestHeader.getNonce()) &&
                Objects.nonNull(requestHeader.getTimestamp());
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

3.4.3 實現(xiàn)nonce的校驗

@Component
public class NonceVerificationHandler implements SecurityVerificationHandler {
    private static final String NONCE_KEY = "x-nonce-";

    @Value("${dailymart.sign.timeout:60000}")
    private long expireTime ;
  
    @Resource
    private DistributedCache distributedCache;

    @Override
    public AuthenticatorResult handler(ProtectedRequest protectedRequest) {
        String nonce = protectedRequest.getRequestHeader().getNonce();
        boolean nonceExists = distributedCache.hasKey(NONCE_KEY + nonce);

        if (nonceExists) {
            return new AuthenticatorResult(false, "請勿重復提交請求");
        } else {
            distributedCache.put(NONCE_KEY + nonce, nonce, expireTime);
            return new AuthenticatorResult(true, "");
        }
    }

    @Override
    public int getOrder() {
        return 3;
    }
}

3.4.4 實現(xiàn)簽名認證

@Component
@Slf4j
public class SignatureVerificationHandler implements SecurityVerificationHandler {
    @Override
    public AuthenticatorResult handler(ProtectedRequest protectedRequest) {

        //1. 服務(wù)端按照規(guī)則重新簽名
        String serverSign = sign(protectedRequest);
        log.info("服務(wù)端簽名結(jié)果: {}", serverSign);

        String clientSign = protectedRequest.getRequestHeader().getSign();
        // 2、獲取客戶端傳遞的簽名
        log.info("客戶端簽名: {}", clientSign);

        if (!Objects.equals(serverSign,clientSign)) {
            return new AuthenticatorResult(false, "請求簽名無效");
        }
        return new AuthenticatorResult(true, "");
    }

    /**
     * 服務(wù)端重建簽名
     * @param protectedRequest 請求體
     * @return 簽名結(jié)果
     */
    private String sign(ProtectedRequest protectedRequest) {
        RequestHeader requestHeader = protectedRequest.getRequestHeader();
        String appId = requestHeader.getAppId();

        String appSecret = getAppSecret(appId);
        // 1、 按照規(guī)則對數(shù)據(jù)進行簽名
        SortedMap<String, Object> requestBody = protectedRequest.getRequestBody();
        requestBody.put("app_id",appId);
        requestBody.put("nonce_number",requestHeader.getNonce());
        requestBody.put("request_time",requestHeader.getTimestamp());

        StringBuilder signBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : requestBody.entrySet()) {
            signBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        signBuilder.append("appSecret=").append(appSecret);

        return DigestUtils.md5DigestAsHex(signBuilder.toString().getBytes()).toUpperCase();
    }


    @Override
    public int getOrder() {
        return 4;
    }

}

3.4.5 責任鏈上下文

@Component
@Slf4j
public class SecurityVerificationChain {
    @Resource
    private List<SecurityVerificationHandler> securityVerificationHandlers;

    public AuthenticatorResult handler(ProtectedRequest protectedRequest){
        AuthenticatorResult authenticatorResult = new AuthenticatorResult(true,"");
        for (SecurityVerificationHandler securityVerificationHandler : securityVerificationHandlers) {
            AuthenticatorResult result = securityVerificationHandler.handler(protectedRequest);
            // 有一個校驗不通過理解返回
            if(!result.isResult()){
                return result;
            }
        }
        return authenticatorResult;

    }

}

組合所有的校驗邏輯,任意一個校驗邏輯不通過則直接返回。

小結(jié)

在本文中,我們深入研究了微服務(wù)架構(gòu)中對外開放接口的安全性保障機制。我們著重關(guān)注了那些暴露在外網(wǎng)的API接口面臨的兩個關(guān)鍵安全問題:篡改和重放。為了應(yīng)對篡改問題,我們引入了雙重手段:采用HTTPS進行加密傳輸,并結(jié)合接口參數(shù)簽名驗證,以確保數(shù)據(jù)傳輸?shù)耐暾院桶踩?。對于重放問題,我們采納了基于nonce和timestamp的方案,以保證請求的唯一性和有效性。

在具體的代碼實現(xiàn)中,我們不僅考慮了文章中提到的安全認證邏輯,還充分考慮了其他可能的校驗規(guī)則。為了更好地組織和管理這些校驗規(guī)則,我們將它們拆分成獨立的模塊,根據(jù)請求路徑動態(tài)選擇相應(yīng)的接口校驗器。在第三方接口校驗邏輯中,我們通過責任鏈的設(shè)計模式實現(xiàn)了具體的校驗規(guī)則,使得代碼邏輯更為模塊化和可擴展。這樣的結(jié)構(gòu)不僅使得每個校驗步驟聚焦于特定的安全性驗證,而且提供了良好的可維護性和可擴展性。

最后給大家一個小建議:對外提供的接口協(xié)議盡量簡單,不要使用Restful接口風格,全部使用post+json或post+form風格的接口協(xié)議即可,這樣對客戶端和服務(wù)端都方便。

責任編輯:武曉燕 來源: JAVA日知錄
相關(guān)推薦

2019-11-20 23:44:29

接口數(shù)據(jù)加密數(shù)據(jù)安全

2021-05-26 08:49:15

API接口安全

2020-11-18 09:37:44

微服務(wù)

2023-10-16 11:12:29

2010-10-08 10:17:59

Web服務(wù)安全

2024-02-22 08:12:41

接口微服務(wù)內(nèi)網(wǎng)服務(wù)

2018-06-25 09:48:00

數(shù)據(jù)安全云服務(wù)

2024-07-08 11:30:35

2023-07-11 08:55:26

系統(tǒng)白名單AO

2024-03-18 08:48:52

Spring多端認證微服務(wù)

2014-06-11 09:36:36

云存儲數(shù)據(jù)安全

2024-03-27 09:01:53

微服務(wù)FeignToken

2012-01-10 10:23:20

鐵路網(wǎng)絡(luò)接口

2010-06-02 13:29:55

2024-11-27 08:47:12

2009-03-04 06:37:00

2021-08-02 09:27:02

微服務(wù)接口場景

2023-02-04 10:08:40

2020-12-01 11:18:34

對外接口枚舉

2011-09-23 10:13:43

點贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 一区二区三区四区五区在线视频 | 午夜tv免费观看 | 自拍第1页| 亚洲一区二区三区高清 | 成人av免费在线观看 | 国产精品性做久久久久久 | 国产日韩欧美中文 | 中文字幕高清av | 亚洲国产成人久久久 | 亚洲成人免费在线 | 午夜久久av| 国产在线观看福利 | 91网站在线播放 | 毛片一级电影 | 国产91丝袜在线18 | 99视频免费看 | 久久9久 | 精品国产精品三级精品av网址 | 永久免费av | 亚洲精品电影网在线观看 | 日本不卡在线观看 | 羞羞视频在线观看免费观看 | 国产高清视频在线 | 精品久久影院 | 成人妇女免费播放久久久 | 久久久久久久国产精品影院 | 91在线一区 | 久久久久国产精品一区二区 | 亚洲欧美国产毛片在线 | 艹逼网| 成人做爰www免费看视频网站 | 精品国产一区二区三区久久 | 国产999精品久久久影片官网 | 日韩视频免费看 | 国产高清在线视频 | 99re热精品视频国产免费 | 亚洲高清视频一区 | 在线观看成人精品 | 久久久久久免费毛片精品 | www.亚洲精品 | 久久国产精品首页 |