简体   繁体   English

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

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

I am trying to generate a valid SAS token (shared access signatures) to connect to the Azure IoT Hub, but I keep getting the error Connection refused: Not authorized when using the token. 我试图生成一个有效的SAS令牌(共享访问签名)以连接到Azure IoT中心,但我不断收到错误Connection refused: Not authorized使用令牌时Connection refused: Not authorized

I know the way I am connecting is working because when using a SAS token generated with the Microsoft Device Explorer ( https://github.com/Azure/azure-iot-sdk-csharp/tree/master/tools/DeviceExplorer ) it works as expected. 我知道我的连接方式有效,因为使用Microsoft设备资源管理器( https://github.com/Azure/azure-iot-sdk-csharp/tree/master/tools/DeviceExplorer )生成的SAS令牌时,它可以工作如预期的那样。

To write the Javascript code I started from this documentation https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1 comparing with some working implementations: 为了编写Javascript代码,我从本文档https://docs.microsoft.com/zh-cn/azure/storage/common/storage-dotnet-shared-access-signature-part-1开始,并与一些可行的实现进行了比较:

What am I doing wrong in the following Javascript implementation? 在以下Javascript实现中我在做什么错? I think it may be related to the SHA256 signature combined with URL escaping the string but I am not sure how to test/verify this. 我认为这可能与结合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;
}

Here is an example of generating SAS token via node.js. 是一个通过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;
};

What am I doing wrong in the following Javascript implementation? 在以下Javascript实现中我在做什么错?

I am not an expert on javascript(node.js). 我不是javascript(node.js)的专家。 Maybe you can figure it out via comparing above code and yours. 也许您可以通过比较上面的代码和您的代码来弄清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM