2
votes

I have to register a device on IoT hub using DPS service. I cannot use the .net SDK as device firmware does not support so we decided to use the REST based API's to do the same.

With C# SDK all I need are the .PFX file with password, DPS_IDSCOPE and device endpoint something like this (xyz.azure-devices-provisioning.net).

Now How I can use above information to do the same with azure rest API.For Authentication I have seen below link which says I have to use SAS token for the same as Azure AD access token wont work.

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

Now If I trust on above link (However I do not think it will work ) then where is the use of certificate .PFX file ?

I have found this official API to register the device .

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

I have not understand how to pass the body information like structure of JSON.I know I have to use x509 as Attestation type but how I will form is it like

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

         };

Or if its a json then what will be the name of attribute ?

enter image description here

Now below are the sample code that I tried to use and getting same error.

Way-1 (Used .PFX as authentication)

  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;
        }
    } 

Way-2 - Using SAS token :

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;
        }
    }

Helper method :

 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;
    }

Now Please answer some body whether I am doing correct or wrong here as I am getting exception.

{StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { x-ms-request-id: 6475343d-5a2e-407a-9e7f-896e0c489307 Strict-Transport-Security: max-age=31536000; includeSubDomains Date: Thu, 28 Feb 2019 11:42:59 GMT Content-Length: 0 }}

Looking forward for the help ...

2

2 Answers

3
votes

Please follow the steps outlined here: https://docs.microsoft.com/en-us/azure/iot-dps/tutorial-net-provision-device-to-hub to first create an Enrollment in DPS for this device using X.509 (no need to use EnrollmentGroup for a single device).

When registering a device with DPS, use the global endpoint - global.azure-devices-provisioning.net. Configure the HTTP client to include the device client certificate. Do not provide a SAStoken from the device.

You can setup the HTTP message content for device registration as follows:

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

Note that the JSON content does NOT include "type" : "x509".

The device endpoint would be as follows:

PUT https://global.azure-devices-provisioning.net/{idScope}/registrations/device1/register?api-version=2018-11-01 (replace idScope with the one from your DPS. A sample idScope would be 0ne00000012)

1
votes

This POST explains it quite well: http://busbyland.com/azure-iot-device-provisioning-service-via-rest-part-1/

Using the endpoint documented here: https://docs.microsoft.com/es-es/rest/api/iot-dps/runtimeregistration/registerdevice

You can manage to register your devices with a HTTPRequest see the CURL Example above:

curl -L -i -X PUT --cert ./chain.pem --key ./iot-device-1.key.pem -H 'Content-Type: application/json' -H 'Content-Encoding:  utf-8' -d '{"registrationId": "iot-device-1", "payload": {"CustomProperty": "CustomValue"}}' https://global.azure-devices-provisioning.net/XXXXXXXXXXX/registrations/iot-device-1/register?api-version=2019-03-31

You could replicate that request in your development environment.

Note that the global.azure-devices-provisioning.net is used which is public and you do not need any authentication/authorization.