[英]NodeJS equivalent of C# code for hmac-sha256 authorization
我正在嘗試轉換此處找到的C#代碼: AMX授權標頭 ,以連接到外部API。 嘗試連接到外部API時,C#代碼有效,但是當我將其轉換為nodeJS解決方案時,它不起作用。
我沒有訪問外部C#API的權限,因此無法更新該端,但是希望有人可以看一下並看到我缺少或做錯的事情:
我的nodejs解決方案:
var request = require('request');
var uuid = require('node-uuid');
var CryptoJS = require('crypto-js');
var URL = "https://urltoexternalAPI.com";
var itemAPPId = "testAPPId";
var APIKey = "testAPIKey";
var requestUri = encodeURIComponent(URL.toLowerCase());
var requestHttpMethod = "GET";
var requestTimeStamp = Math.floor(new Date().getTime() / 1000).toString();
var nonce = uuid.v1().replace(/-/g, '');
//I excluded the content hashing part as the API Im hitting is a GET request with no body content
var signatureRawData = itemAPPId + requestHttpMethod + requestUri + requestTimeStamp + nonce;
var secretKeyByteArray = CryptoJS.enc.Base64.parse(APIKey);
var signature = CryptoJS.enc.Utf8.parse(signatureRawData);
var signatureBytes = CryptoJS.HmacSHA256(signature, secretKeyByteArray);
var requestSignatureBase64String = signatureBytes.toString(CryptoJS.enc.Base64);
request({
url: URL,
headers: {
'Authorization': "amx "+itemAPPId+":"+requestSignatureBase64String+":"+nonce+":"+requestTimeStamp
}
}, function (error, response, body) {
if (response.statusCode != 200) {
console.log("Fail");
} else {
console.log("Success");
}
});
我想到了! 如果有人遇到此問題,他們可能會發現以下幫助:
以下C#代碼與nodeJS的工作原理略有不同: System.Web.HttpUtility.UrlEncode(request.RequestUri.AbsoluteUri.ToLower());
最初,我原樣復制了此功能,並編寫了等效的nodejs:
var requestUri = encodeURIComponent(URL.toLowerCase());
C#中URL的編碼使所有內容都小寫-例如: https://變為https%3a%2f% 2f-而nodeJS大寫其編碼字符-https %3A%2F% 2F-這是導致錯誤的原因散列。
解決方案是僅在URL編碼完成后將小寫函數移至。 像這樣:
var requestUri = encodeURIComponent(URL).toLowerCase();
看起來很簡單,但是當嘗試復制C#解決方案時,您可能不會發現兩個URL編碼器的工作方式不同。
const fetch = require("node-fetch");
const uuid = require("uuid");
const crypto = require('crypto');
var URL = "https://urltoapi.com";
var itemAPPId = config.itemAPPId;
var APIKey = config.itemAPIKey;
var requestUri = encodeURIComponent(URL).toLowerCase();
var requestHttpMethod = "GET"; //should be dynamic
var requestTimeStamp = Math.floor(new Date().getTime() / 1000).toString();
var nonce = uuid.v1().replace(/-/g, '');
var signatureRawData = itemAPPId + requestHttpMethod + requestUri + requestTimeStamp + nonce;
var key = Buffer.from(APIKey, 'base64');
var requestSignatureBase64String = crypto.createHmac('sha256', key).update(signatureRawData, 'utf8').digest('base64');
const hitExternalAPI = async url => {
try {
const res = await fetch(url, { method: 'GET', headers: { "Authorization": "amx "+itemAPPId+":"+requestSignatureBase64String+":"+nonce+":"+requestTimeStamp } })
.then(res => {
console.log(res.ok);
});
} catch (error) {
console.log("Error",error);
}
};
hitExternalAPI(URL);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.