使用Azure设备配置服务的rest API注册设备?

问题描述 投票:0回答:1

我必须使用DPS服务在IoT集线器上注册设备。我不能使用.net SDK,因为设备固件不支持,所以我们决定使用基于REST的API来做同样的事情。

使用C#SDK,我需要的是带有密码的.PFX文件,DPS_IDSCOPE和类似的设备端点(xyz.azure-devices-provisioning.net)。

现在,我如何使用上述信息对azure rest API执行相同操作。对于身份验证,我在下面看到链接,其中说我必须使用SAS令牌与Azure AD访问令牌相同。

https://social.msdn.microsoft.com/Forums/en-US/19183e82-437e-4d6f-8498-ed33ba18a3fa/creating-iot-device-with-azure-dps-via-rest?forum=azureiothub

现在,如果我信任上面的链接(但我认为它不会起作用)那么使用证书.PFX文件在哪里?

我找到了这个官方API来注册设备。

https://docs.microsoft.com/en-us/rest/api/iot-dps/runtimeregistration/registerdevice

我不明白如何传递JSON结构的身体信息。我知道我必须使用x509作为Attestation类型,但我将如何形成就像它一样

  var pairs = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("registrationId", "device1"),
            new KeyValuePair<string, string>("type", "x509"),

         };

或者如果它是一个json那么属性的名称是什么?

enter image description here

下面是我尝试使用并获得相同错误的示例代码。

Way-1(使用.PFX作为身份验证)

  public static void RegisterDeviceWithEnrollementGroup()
    {
        try
        {
            var handler = new WebRequestHandler();
            var certFile = Path.Combine(@"C:\IoT\", "device1.pfx");
            handler.ClientCertificates.Add(new X509Certificate2(certFile, "certificatepassword"));
            HttpClient client4 = new HttpClient(handler);

            client4.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client4.BaseAddress = new Uri("https://XYZ.azure-devices-provisioning.net/scopeid/registrations/device1/register?api-version=2018-11-01");
            string content = Newtonsoft.Json.JsonConvert.SerializeObject(null);
            var httpContent3 = new StringContent(content, Encoding.UTF8, "application/json");


            var pairs = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("registrationId", "device1"),
            new KeyValuePair<string, string>("type", "x509"),

         };

            var content2 = new FormUrlEncodedContent(pairs);


            HttpResponseMessage response4 = client4.PutAsync(client4.BaseAddress.ToString(), content2).Result;

            var commandResult = string.Empty;

            if (response4.IsSuccessStatusCode)
            {
                commandResult = response4.Content.ReadAsStringAsync().Result;
            }
            else
            {
                commandResult = response4.Content.ReadAsStringAsync().Result;
            }

            Console.WriteLine("IoT hub API call result - " + commandResult);
        }
        catch (Exception)
        {
            throw;
        }
    } 

方式2 - 使用SAS令牌:

public static void RegisterDeviceWithEnrollementGroup(){try { HttpClient client4 = new HttpClient();

            var sas = generateSasToken("XYZ.azure-devices-provisioning.net", "key", "provisioningserviceowner");
             client4.DefaultRequestHeaders.Add("Authorization", sas);

            client4.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            client4.BaseAddress = new Uri("https://XYZ.azure-devices-provisioning.net/scopeid/registrations/device1/register?api-version=2018-11-01");
            string content = Newtonsoft.Json.JsonConvert.SerializeObject(null);
            var httpContent3 = new StringContent(content, Encoding.UTF8, "application/json");


            var pairs = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("registrationId", "device1"),
            new KeyValuePair<string, string>("type", "x509"),

         };

            var content2 = new FormUrlEncodedContent(pairs);


            HttpResponseMessage response4 = client4.PutAsync(client4.BaseAddress.ToString(), content2).Result;

            var commandResult = string.Empty;

            if (response4.IsSuccessStatusCode)
            {
                commandResult = response4.Content.ReadAsStringAsync().Result;
            }
            else
            {
                commandResult = response4.Content.ReadAsStringAsync().Result;
            }

            Console.WriteLine("IoT hub API call result - " + commandResult);
        }
        catch (Exception)
        {
            throw;
        }
    }

辅助方法:

 public static string generateSasToken(string resourceUri, string key, string policyName, int expiryInSeconds = 3600)
    {
        TimeSpan fromEpochStart = DateTime.UtcNow - new DateTime(1970, 1, 1);
        string expiry = Convert.ToString((int)fromEpochStart.TotalSeconds + expiryInSeconds);

        string stringToSign = WebUtility.UrlEncode(resourceUri) + "\n" + expiry;

        HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));
        string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

        string token = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}", WebUtility.UrlEncode(resourceUri), WebUtility.UrlEncode(signature), expiry);

        if (!String.IsNullOrEmpty(policyName))
        {
            token += "&skn=" + policyName;
        }

        return token;
    }

现在请回答一些身体我是否在这里正确或错误,因为我得到例外。

{StatusCode:415,ReasonPhrase:'Unsupported Media Type',版本:1.1,内容:System.Net.Http.StreamContent,标题:{x-ms-request-id:6475343d-5a2e-407a-9e7f-896e0c489307 Strict-Transport - 安全:max-age = 31536000; includeSubDomains日期:星期四,2019年2月28日11:42:59 GMT内容长度:0}}

期待着帮助......

azure x509certificate azure-iot-hub azure-iot-hub-device-management
1个回答
0
投票

请按照此处列出的步骤进行操作:https://docs.microsoft.com/en-us/azure/iot-dps/tutorial-net-provision-device-to-hub首先使用X.509为此设备创建DPS注册(无需为单个设备使用EnrollmentGroup)。

使用DPS注册设备时,请使用全局端点 - global.azure-devices-provisioning.net。配置HTTP客户端以包含设备客户端证书。不要从设备提供SAStoken。

您可以为设备注册设置HTTP消息内容,如下所示:

httpRequest.Content = new StringContent(“{\”registrationId \“:\”device1 \“}”,Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(“application / json; charset = utf-8”);

请注意,JSON内容不包含“type”:“x509”。

设备端点如下:

PUT https://global.azure-devices-provisioning.net/ {idScope} / registrations / device1 / register?api-version = 2018-11-01(用你的DPS替换idScope。示例idScope将为0ne00000012)

© www.soinside.com 2019 - 2024. All rights reserved.