我正在尝试通过以下链接使用 Azure 物联网中心 REST API 创 build 备
我的http数据就像
{
"status":"connected",
"authentication":{ "symmetricKey":{
"primaryKey":"key in shared access policies",
"secondaryKey":"key in shared access policies"}
},
"statusReason":"reason",
"deviceId":"test123"
}
我的标题就像
["Content-Type": "application/json", "Authorization": "SharedAccessSignature sig=(key in shared access policies public key)=&se=1481687791&skn=iothubowner&sr=(my iot hub name).azure-devices.net%2fdevices%2ftest123"]
但是我收到错误 401
{"Message":"ErrorCode:IotHubUnauthorizedAccess;Unauthorized","ExceptionMessage":"Tracking ID:(tracking id )-TimeStamp:12/14/2016 03:15:17"}
有人知道如何修复它,或者跟踪异常消息吗?
最佳答案
401 的问题可能在于您计算 SAS 的方式。 计算 IoT 中心 SAS 的完整过程(用 C# 编写)是:
private static readonly DateTime epochTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
public static string SharedAccessSignature(string hostUrl, string policyName, string policyAccessKey, TimeSpan timeToLive)
{
if (string.IsNullOrWhiteSpace(hostUrl))
{
throw new ArgumentNullException(nameof(hostUrl));
}
var expires = Convert.ToInt64(DateTime.UtcNow.Add(timeToLive).Subtract(epochTime).TotalSeconds).ToString(CultureInfo.InvariantCulture);
var resourceUri = WebUtility.UrlEncode(hostUrl.ToLowerInvariant());
var toSign = string.Concat(resourceUri, "\n", expires);
var signed = Sign(toSign, policyAccessKey);
var sb = new StringBuilder();
sb.Append("sr=").Append(resourceUri)
.Append("&sig=").Append(WebUtility.UrlEncode(signed))
.Append("&se=").Append(expires);
if (!string.IsNullOrEmpty(policyName))
{
sb.Append("&skn=").Append(WebUtility.UrlEncode(policyName));
}
return sb.ToString();
}
private static string Sign(string requestString, string key)
{
using (var hmacshA256 = new HMACSHA256(Convert.FromBase64String(key)))
{
var hash = hmacshA256.ComputeHash(Encoding.UTF8.GetBytes(requestString));
return Convert.ToBase64String(hash);
}
}
如果您想在 IoTHub 中创 build 备,您必须拥有具有完全权限的策略,这意味着: 注册表读写、服务连接和设备连接。 如果您需要一个完整的功能示例,用 C# 编写,了解如何使用 IoT 中心 REST API 创 build 备、检查设备是否存在并向 IoT 中心发送消息,我已经写过 this post关于它(该帖子是西类牙语的,但我可以想象您需要的只是代码)。
关于rest - Azure IOT 中心 Rest API 未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41134535/