0
votes

in azure iot hub we have multiple types of connection string

to register a device i can use SharedAccessKeyName=iothubowner but to send a messages to device i need to use SharedAccessKeyName=device coonection string as i'm going to generate deviceId at runtime.

So how can i register device using SharedAccessKeyName=device so that I can use same connection string to send messages to iot hub device.

code to register device -

class Program
    {
        static RegistryManager registryManager;
        static string connectionString = "HostName=mydemo.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=key!";
        private static async Task AddDeviceAsync()
    {
        string deviceId = "dummydevice";
        Device device;
        try
        {
            device = await registryManager.AddDeviceAsync(new Device(deviceId));
        }
        catch (DeviceAlreadyExistsException)
        {
            device = await registryManager.GetDeviceAsync(deviceId);
        }
        Console.WriteLine("Generated device key: {0}", device.Authentication.SymmetricKey.PrimaryKey);
    }
    static void Main(string[] args)
    {
        registryManager = RegistryManager.CreateFromConnectionString(connectionString);
        AddDeviceAsync().Wait();
        Console.ReadLine();
    }
1

1 Answers

3
votes

For a device to connect to an IoT hub, there are two types of connection string you can use:

  • A hub-scoped shared access policy that looks like: HostName=yourhubname.azure-devices.net;SharedAccessKeyName=device;SharedAccessKey=yourkey
  • A device connection string that looks like: HostName=yourhubname.azure-devices.net;DeviceId=yourdeviceid;SharedAccessKey=yourdevicekey

You can find the first in the Portal on your hub's "Shared access policies" page. You can find the second in the portal on a device's detail page.

The following section in the docs explains how you can use the two different types of key: https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security#use-sas-tokens-in-a-device-app