API網關Kong系列(四)認證配置


目前根據業務需要先介紹2種認證插件:Key Authentication 及 HMAC-SHA1 認證

  Key Authentication

 

向API添加密鑰身份驗證(也稱為API密鑰)。 然后,消費者可以在 querystring 參數或 Header 頭中添加其密鑰,以驗證其請求。


 進入之前部署好的kong-ui,選擇plugins,點擊+號

 

按需求輸入參數

同樣創建一個消費者

 其中客戶Id為選填

生成后進入消費者列表,編輯該用戶,按一下操作生成對應的key。

同時我們可以看到消費者中包含有其他插件所需的屬性等,可以按需自己生成。

 

 

 添加后如下

 

 

使用起來也很簡單,將key(之前添加插件是設置的key名稱)插入header值即可

 

如果驗證錯誤則返回403

 

 
  HMAC Authentication

為您的API添加HMAC簽名身份驗證以建立使用者的身份。 插件將在代理授權和授權Header中檢查有效的簽名(按此順序)。 這個插件實現遵循draft-cavage-http-signatures-00草案略有改變的簽名方案。

 根據如上方法,同理增加HMAC認證憑證

同理加入HMAC插件

 

 

 HMAC-SHA1,C#代碼實現:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Security.Cryptography
{
    public static class HMAC_SHA1
    {
        public static string Sign(string text, string key, string inputCharset = "utf-8")
        {
            Encoding _encode = Encoding.GetEncoding(inputCharset);
            byte[] _byteData = Encoding.GetEncoding(inputCharset).GetBytes(text);
            HMACSHA1 _hmac = new HMACSHA1(_encode.GetBytes(key));

            using (CryptoStream _cs = new CryptoStream(Stream.Null, _hmac, CryptoStreamMode.Write))
            {
                _cs.Write(_byteData, 0, _byteData.Length);
            }
            return Convert.ToBase64String(_hmac.Hash);
        }
    }
}

 

請求的時候主要是header中

Authorization 的構造,根據官方文檔

Authorization: hmac username="bob", algorithm="hmac-sha1", headers="date content-md5", signature="Base64(HMAC-SHA1(signing string))"

如果有多個Header的話,header名稱用空格隔開,注意官方文檔中的"date"如今應該改成"x-date",date的格式請使用GMT時間諸如"Wed, 01 Mar 2017 05:05:24 GMT"

官方文檔中加密字符串:

date: Fri, 09 Oct 2015 00:00:00 GMT\ncontent-md5: lCMsW4/JJy9vc6HjbraPzw==

注意也要將date修改成x-date,如果沒有content-md5這個頭,那就不用加\n,直接為

x-date: Fri, 09 Oct 2015 00:00:00 GMT

 

這邊提供一組正確的加密字串,供大家實現算法后驗證

secret:secret7496

加密前字符串:x-date: Wed, 01 Mar 2017 05:05:24 GMT

摘要字符串為:XefFQYm8HRXsocJHF4ibDEPWW3k=

 

重要備注:

這個HMAC主要碰到2類錯誤

1.HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication

這個錯誤主要2種情況都跟日期有關

  1)服務器時間跟客戶端發出去的x-date的間隔時間超過之前定義的clock skew秒數(通過docker容器安裝的容易產生這個問題)

  2)請確認是GMT時間格式

  3)把date改成x-date

2.HMAC signature does not match

這個就是簽名算法有問題了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM