簡體   English   中英

如何通過Javascript(node.js)生成Azure SAS令牌

[英]How to generate an Azure SAS token via Javascript (node.js)

我試圖生成一個有效的SAS令牌(共享訪問簽名)以連接到Azure IoT中心,但我不斷收到錯誤Connection refused: Not authorized使用令牌時Connection refused: Not authorized

我知道我的連接方式有效,因為使用Microsoft設備資源管理器( https://github.com/Azure/azure-iot-sdk-csharp/tree/master/tools/DeviceExplorer )生成的SAS令牌時,它可以工作如預期的那樣。

為了編寫Javascript代碼,我從本文檔https://docs.microsoft.com/zh-cn/azure/storage/common/storage-dotnet-shared-access-signature-part-1開始,並與一些可行的實現進行了比較:

在以下Javascript實現中我在做什么錯? 我認為這可能與結合URL轉義字符串的SHA256簽名有關,但是我不確定如何測試/驗證它。

const crypto = require('crypto');

// on the Azure Portal:
// sharedAccessKeyName is the "policy" field
// sharedAccessKeyValue is the "primary key"

const sign = (iotHubName, expirtyDeltaInSecondsFromNow, sharedAccessKeyName, sharedAccessKeyValue) => {
  // URL encode the IoT Hub host
  const encodedSasUrl = encodeURI(`${iotHubName}.azure-devices.net`.toLowerCase());
  // calculate the expiry end datetime as an epoch
  const expiry = parseInt(Date.now() / 1000 + expirtyDeltaInSecondsFromNow);
  // combine the previous two pieces of information
  const stringToSign = `${encodedSasUrl}\n${expiry}`;
  // sign the string using the primary key (sharedAccessKeyValue) and SHA256
  const hmac = crypto.createHmac('sha256', sharedAccessKeyValue);
  hmac.update(stringToSign);
  const hash = hmac.digest('hex');
  // encode the signed hash to base64 (making sure it's URL escaped)
  const encodedSignature = hash.toString('base64');
  // put all together into the SAS token
  const sasToken = `SharedAccessSignature sig=${encodedSignature}&se=${expiry}&skn=${sharedAccessKeyName}&sr=${encodedSasUrl}`;
  console.log("sasToken:", sasToken);
  return sasToken;
}

是一個通過node.js生成SAS令牌的示例。

var generateSasToken = function(resourceUri, signingKey, policyName, expiresInMins) {
    resourceUri = encodeURIComponent(resourceUri);

    // Set expiration in seconds
    var expires = (Date.now() / 1000) + expiresInMins * 60;
    expires = Math.ceil(expires);
    var toSign = resourceUri + '\n' + expires;

    // Use crypto
    var hmac = crypto.createHmac('sha256', new Buffer(signingKey, 'base64'));
    hmac.update(toSign);
    var base64UriEncoded = encodeURIComponent(hmac.digest('base64'));

    // Construct autorization string
    var token = "SharedAccessSignature sr=" + resourceUri + "&sig="
    + base64UriEncoded + "&se=" + expires;
    if (policyName) token += "&skn="+policyName;
    return token;
};

在以下Javascript實現中我在做什么錯?

我不是javascript(node.js)的專家。 也許您可以通過比較上面的代碼和您的代碼來弄清楚。

暫無
暫無

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

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