gpt4 book ai didi

node.js - 如何通过 Javascript (node.js) 生成 Azure SAS token

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:09 24 4
gpt4 key购买 nike

我正在尝试生成有效的 SAS token (共享访问签名)来连接到 Azure IoT 中心,但我不断收到错误 Connection refused: Not authorized使用 token 时。

我知道我的连接方式有效,因为当使用 Microsoft Device Explorer ( https://github.com/Azure/azure-iot-sdk-csharp/tree/master/tools/DeviceExplorer ) 生成的 SAS token 时,它会按预期工作。

为了编写 Javascript 代码,我从本文档 https://learn.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1 开始与一些工作实现进行比较:

在下面的 Javascript 实现中我做错了什么?我认为这可能与 SHA256 签名结合 URL 转义字符串有关,但我不确定如何测试/验证这一点。

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是通过node.js生成SAS token 的示例。

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(node.js) 专家。也许你可以通过比较上面的代码和你的代码来找出答案。

关于node.js - 如何通过 Javascript (node.js) 生成 Azure SAS token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51728649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com