Azure IOT 中心 Rest API 未经授权

ddf*_*ish 4 rest azure azure-iot-hub

我正在尝试通过以下链接使用 Azure 物联网中心 REST API 创建设备

创建新的设备标识

控制对 IoT 中心的访问

我的http数据就像

{
    "status":"connected",
    "authentication":{ "symmetricKey":{
                "primaryKey":"key in shared access policies",
                "secondaryKey":"key in shared access policies"}
             },
    "statusReason":"reason",
    "deviceId":"test123"
}
Run Code Online (Sandbox Code Playgroud)

我的标题就像

 ["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"]
Run Code Online (Sandbox Code Playgroud)

但我收到错误 401

{"Message":"ErrorCode:IotHubUnauthorizedAccess;Unauthorized","ExceptionMessage":"Tracking ID:(tracking id )-TimeStamp:12/14/2016 03:15:17"}
Run Code Online (Sandbox Code Playgroud)

有人知道如何修复它或跟踪异常消息吗?

Fab*_*ulo 5

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您想在 IoTHub 中创建设备,您必须拥有具有完全权限的策略,这意味着:注册表读取和写入、服务连接和设备连接。如果您需要 C# 中的完整功能示例,了解如何使用 IoT 中心 REST API 创建设备、检查设备是否存在并向 IoT 中心发送消息,我已经写了一篇关于它的文章(该文章是西班牙语,但我可以想象您需要的只是代码)。