簡體   English   中英

編碼/加密node.js中的Azure Log Analytics授權標頭

[英]Encoding/Encrypting the Azure Log Analytics Authorization Header in node.js

我一直在嘗試讓Log Collector API在node.js Azure函數中運行,但是卡在403 / Forbidden錯誤上,這表明我沒有正確形成授權標頭。 完整的代碼在github存儲庫中:

https://github.com/sportsmgmt-labs/Azure-Log-Analytics-Node-Function

Data Collector API文檔在這里:

https://docs.microsoft.com/en-us/azure/log-analytics/log-analytics-data-collector-api

授權標頭的格式應如下:

授權:SharedKey {WorkspaceID}:{Signature}

簽名的編碼/加密方式如下:

Base64編碼(HMAC-SHA256(UTF8(StringToSign)))

這是我創建授權標頭的代碼:

var contentLength = Buffer.byteLength(req.body['log-entry'], 'utf8');

var authorization = 'POST\n' + contentLength + '\napplication/json\nx-ms-date:' + processingDate + '\n/api/logs';

// encode string using Base64(HMAC-SHA256(UTF8(StringToSign)))
authorization = crypto.createHmac('sha256', sharedKey).update(authorization.toString('utf8')).digest('base64');

authorization = 'Authorization: SharedKey ' + workspaceId + ':' + authorization;

服務器的響應為:

{“錯誤”:“ InvalidAuthorization”,“消息”:“在授權標頭中指定了無效的方案”}

有人可以幫我了解我在做什么錯嗎? 謝謝!

編輯:這是執行此操作的Python代碼:

def build_signature(customer_id, shared_key, date, content_length, method, content_type, resource):
    x_headers = 'x-ms-date:' + date
    string_to_hash = method + "\n" + str(content_length) + "\n" + content_type + "\n" + x_headers + "\n" + resource
    bytes_to_hash = bytes(string_to_hash).encode('utf-8')  
    decoded_key = base64.b64decode(shared_key)
    encoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_hash, digestmod=hashlib.sha256).digest())
    authorization = "SharedKey {}:{}".format(customer_id,encoded_hash)
    return authorization

...以及C#代碼:

    static void Main()
    {
        // Create a hash for the API signature
        var datestring = DateTime.UtcNow.ToString("r");
        string stringToHash = "POST\n" + json.Length + "\napplication/json\n" + "x-ms-date:" + datestring + "\n/api/logs";
        string hashedString = BuildSignature(stringToHash, sharedKey);
        string signature = "SharedKey " + customerId + ":" + hashedString;

        PostData(signature, datestring, json);
    }

    // Build the API signature
    public static string BuildSignature(string message, string secret)
    {
        var encoding = new System.Text.ASCIIEncoding();
        byte[] keyByte = Convert.FromBase64String(secret);
        byte[] messageBytes = encoding.GetBytes(message);
        using (var hmacsha256 = new HMACSHA256(keyByte))
        {
            byte[] hash = hmacsha256.ComputeHash(messageBytes);
            return Convert.ToBase64String(hash);
        }
    }

您需要先對共享密鑰進行解碼。 請嘗試更改以下代碼行:

authorization = crypto.createHmac('sha256', sharedKey).update(authorization.toString('utf8')).digest('base64');
authorization = 'Authorization: SharedKey ' + workspaceId + ':' + authorization;

至:

authorization = crypto.createHmac('sha256', new Buffer(sharedKey, 'base64')).update(authorization, 'utf-8').digest('base64');
var signature = 'SharedKey ' + workspaceId + ':' + authorization;

然后,請求標頭將如下所示:

headers: {
    'content-type': 'application/json',
    'Authorization': signature,
    'Log-Type': <log_type>,
    'x-ms-date': processingDate
},

Node.js代碼示例

var request = require('request');
var crypto = require('crypto');

// Azure Log Analysis credentials
var workspaceId = 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
var sharedKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

var apiVersion = '2016-04-01';
var processingDate = new Date().toUTCString();

var jsonData = [{
   "slot_ID": 12345,
    "ID": "5cdad72f-c848-4df0-8aaa-ffe033e75d57",
    "availability_Value": 100,
    "performance_Value": 6.954,
    "measurement_Name": "last_one_hour",
    "duration": 3600,
    "warning_Threshold": 0,
    "critical_Threshold": 0,
    "IsActive": "true"
},
{   
    "slot_ID": 67890,
    "ID": "b6bee458-fb65-492e-996d-61c4d7fbb942",
    "availability_Value": 100,
    "performance_Value": 3.379,
    "measurement_Name": "last_one_hour",
    "duration": 3600,
    "warning_Threshold": 0,
    "critical_Threshold": 0,
    "IsActive": "false"
}]

var body = JSON.stringify(jsonData);    

var contentLength = Buffer.byteLength(body, 'utf8');

var stringToSign = 'POST\n' + contentLength + '\napplication/json\nx-ms-date:' + processingDate + '\n/api/logs';
var signature = crypto.createHmac('sha256', new Buffer(sharedKey, 'base64')).update(stringToSign, 'utf-8').digest('base64');
var authorization = 'SharedKey ' + workspaceId + ':' + signature;

var headers = {
    "content-type": "application/json", 
    "Authorization": authorization,
    "Log-Type": 'WebMonitorTest',
    "x-ms-date": processingDate
};

var url = 'https://' + workspaceId + '.ods.opinsights.azure.com/api/logs?api-version=' + apiVersion;

request.post({url: url, headers: headers, body: body}, function (error, response, body) {
  console.log('error:', error); 
  console.log('statusCode:', response && response.statusCode); 
  console.log('body:', body); 
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM