目前根據業務須要先介紹2種認證插件:Key Authentication 及 HMAC-SHA1 認證算法
Key Authenticationdocker
向API添加密鑰身份驗證(也稱爲API密鑰)。 而後,消費者能夠在 querystring 參數或 Header 頭中添加其密鑰,以驗證其請求。服務器
進入以前部署好的kong-ui,選擇plugins,點擊+號ui
按需求輸入參數加密
一樣建立一個消費者spa
其中客戶Id爲選填插件
生成後進入消費者列表,編輯該用戶,按一下操做生成對應的key。代理
同時咱們能夠看到消費者中包含有其餘插件所需的屬性等,能夠按需本身生成。code
添加後以下blog
使用起來也很簡單,將key(以前添加插件是設置的key名稱)插入header值便可
若是驗證錯誤則返回403
爲您的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
這個就是簽名算法有問題了