var resourceName = postman.getEnvironmentVariable("resourceName");
var resourceKey = postman.getEnvironmentVariable("resourceKey");
var tokenExpirationPeriod = postman.getEnvironmentVariable("tokenExpirationPeriod");
var policyKeyName = postman.getEnvironmentVariable("policyKeyName");
postman.clearEnvironmentVariable("deviceTwinSasToken"); // clear out token on first run.
// See this doc for details: https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security
var resourceUri = encodeURIComponent(resourceName + '.azure-devices.net'); // The resource uri
var expiry = Math.ceil((Date.now() / 1000) + tokenExpirationPeriod * 60); // Expire the token 60 minutes from now
var uriExpiry = resourceUri + '\n' + expiry; // this is the string format to gen signature from
var decodedKey = CryptoJS.enc.Base64.parse(resourceKey); // The SHA256 key is the Base64 decoded version of the IoT Hub key
var signature = CryptoJS.HmacSHA256(uriExpiry, decodedKey); // The signature generated from the decodedKey
var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); // The url encoded version of the Base64 signature
// Construct authorization string (shared access signature)
var deviceTwinSasToken = "SharedAccessSignature sr=" + resourceUri + "&sig=" + encodedUri + "&se=" + expiry;
// Add token if one is present
if (policyKeyName) {
deviceTwinSasToken += "&skn="+ policyKeyName;
}
// Put in variable to be used in other requests.
postman.setEnvironmentVariable("deviceTwinSasToken", deviceTwinSasToken);
console.log("Shared Access Signature:" + postman.getEnvironmentVariable("deviceTwinSasToken"));
3 回答
从你的图片开始,您使用了指定的设备 SAS 令牌。当您需要使用 IoT Hub SAS 令牌时,它可以授予访问控制和权限。您可以使用 Device Explorer 获取它,如下所示:
成功发布 Get 请求后,您将获得设备双胞胎信息,在邮递员中,它看起来像这样:
您似乎正在尝试使用 REST API 从“设备”(因为您使用从 Device ID/Key 对生成的 SAS 令牌)访问设备双胞胎。这不能完成,因为“设备”的设备双胞胎的交互是通过 MQTT 完成的,而不是通过 HTTP 完成的(请参阅下面的链接,了解 IoT Hub 端点和双胞胎上的文档)。如果您想从设备使用设备 Twins,我建议您查看 Azure IOT 设备 SDK。如果您想了解有关使用 MQTT 的更多信息,可以阅读这个。
但是,如果您想从后端角度使用设备 Twins(如使用为设备设置所需属性的后端应用程序,读取设备报告的属性并使用标签),则需要使用从其中一个 IoT 生成的 SAS 令牌集线器共享访问策略 name/key(不是设备凭据)。尝试使用相同的设备资源管理器工具生成 SAS 令牌,但在“配置”选项卡上为此。
设备双胞胎上的一些文档可以帮助使这一切更加清晰:
设备双胞胎描述
物联网中心端点
您可以使用 Postman Pre-request 脚本沙箱生成 SAS 令牌。这是我写的博客文章,详细介绍了生成 SAS 令牌所需的一切。 http://blog.jongallant.com/2017/02/azure-iot-hub-device-twin-rest-apis-postman-newman/
这是一个 Postman 集合,它将向您展示如何执行 API:https://www.getpostman.com/collections/84a38008cd07accf565e
这里有更多 Postman/Azure 相关帖子(也是我自己的帖子):http://blog.jongallant.com/tags/postman/
这是我在 Pre-request 脚本沙箱中使用的代码: