Example #1
0
        /// <summary>
        /// Provisions a device to a starting hub, tries to open a connection, send telemetry,
        /// and (if supported by the protocol) send a twin update. Then, this method updates the enrollment
        /// to provision the device to a different hub. Based on the provided reprovisioning settings, this
        /// method then checks that the device was/was not reprovisioned as expected, and that the device
        /// did/did not migrate twin data as expected.
        /// </summary>
        public async Task ProvisioningDeviceClient_ReprovisioningFlow(
            Client.TransportType transportProtocol,
            AttestationMechanismType attestationType,
            EnrollmentType?enrollmentType,
            bool setCustomProxy,
            ReprovisionPolicy reprovisionPolicy,
            AllocationPolicy allocationPolicy,
            CustomAllocationDefinition customAllocationDefinition,
            ICollection <string> iotHubsToStartAt,
            ICollection <string> iotHubsToReprovisionTo,
            string proxyServerAddress = null)
        {
            ProvisioningServiceClient provisioningServiceClient = CreateProvisioningService(s_proxyServerAddress);
            string groupId = _devicePrefix + AttestationTypeToString(attestationType) + "-" + Guid.NewGuid();

            bool twinOperationsAllowed = transportProtocol != Client.TransportType.Http1;

            using ProvisioningTransportHandler transport = ProvisioningE2ETests.CreateTransportHandlerFromName(transportProtocol);
            using SecurityProvider security = await CreateSecurityProviderFromName(
                      attestationType,
                      enrollmentType,
                      groupId,
                      reprovisionPolicy,
                      allocationPolicy,
                      customAllocationDefinition,
                      iotHubsToStartAt)
                                              .ConfigureAwait(false);

            //Check basic provisioning
            if (ProvisioningE2ETests.ImplementsWebProxy(transportProtocol) && setCustomProxy)
            {
                transport.Proxy = (proxyServerAddress != null) ? new WebProxy(s_proxyServerAddress) : null;
            }

            ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                s_globalDeviceEndpoint,
                Configuration.Provisioning.IdScope,
                security,
                transport);

            using var cts = new CancellationTokenSource(PassingTimeoutMiliseconds);
            DeviceRegistrationResult result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false);

            ValidateDeviceRegistrationResult(result);
            Client.IAuthenticationMethod auth = CreateAuthenticationMethodFromSecurityProvider(security, result.DeviceId);
            await ConfirmRegisteredDeviceWorks(result, auth, transportProtocol, twinOperationsAllowed).ConfigureAwait(false);

            //Check reprovisioning
            await UpdateEnrollmentToForceReprovision(enrollmentType, provisioningServiceClient, iotHubsToReprovisionTo, security, groupId).ConfigureAwait(false);

            result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false);

            ConfirmDeviceInExpectedHub(result, reprovisionPolicy, iotHubsToStartAt, iotHubsToReprovisionTo, allocationPolicy);
            await ConfirmDeviceWorksAfterReprovisioning(result, auth, transportProtocol, reprovisionPolicy, twinOperationsAllowed).ConfigureAwait(false);

            if (attestationType != AttestationMechanismType.X509) //x509 enrollments are hardcoded, should never be deleted
            {
                await ProvisioningE2ETests.DeleteCreatedEnrollmentAsync(enrollmentType, provisioningServiceClient, security, groupId).ConfigureAwait(false);
            }
        }
Example #2
0
        public static async Task <DeviceRegistrationResult> RegisterWithModelAsync(this ProvisioningDeviceClient dpsClient, string modelId, ILogger log)
        {
            var res = await dpsClient.RegisterAsync(GetProvisionPayload(modelId));

            log.LogInformation("First DPS call with Model ID, result: " + res.Status);
            while (res.Status != ProvisioningRegistrationStatusType.Assigned && times++ < 3)
            {
                res = await dpsClient.RegisterAsync(GetProvisionPayload(modelId));

                log.LogInformation($"Next DPS call: {times} with Model ID, result: " + res.Status);
                await Task.Delay((2 ^ times) * 1000);
            }
            return(res);
        }
        public static async Task RunSample(X509Certificate2 certificate)
        {
            using (var security = new SecurityClientX509(certificate))
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(s_idScope, security, transport);

                    Console.Write("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync();

                    Console.WriteLine($"{result.Status}");
                    Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        return;
                    }

                    IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, certificate);
                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth))
                    {
                        Console.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync();

                        Console.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage")));

                        Console.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync();
                    }
                }
        }
Example #4
0
        public async Task ProvisioningDeviceClient_InvalidGlobalAddress_Register_Fail(
            string transportType,
            string securityType,
            X509EnrollmentType?x509EnrollmentType,
            TransportFallbackType?transportFallback)
        {
            if (!ConfigurationFound())
            {
                _log.WriteLine("Provisioning test configuration not found. Result inconclusive.");
                return;
            }

            using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, transportFallback))
                using (SecurityProvider security = CreateSecurityProviderFromName(securityType, x509EnrollmentType))
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                        InvalidGlobalAddress,
                        Configuration.Provisioning.IdScope,
                        security,
                        transport);

                    var cts = new CancellationTokenSource(FailingTimeoutMiliseconds);

                    _log.WriteLine("ProvisioningClient RegisterAsync . . . ");
                    var exception = await Assert.ThrowsExceptionAsync <ProvisioningTransportException>(
                        () => provClient.RegisterAsync(cts.Token)).ConfigureAwait(false);

                    _log.WriteLine($"Exception: {exception}");
                }
        }
        // This method receives the the provisioning device client and security
        // instances created earlier.
        private static async Task <DeviceClient> ProvisionDevice(
            ProvisioningDeviceClient provisioningDeviceClient,
            SecurityProviderSymmetricKey security)
        {
            // The provisioningDeviceClient.RegisterAsync()
            // is called, which returns a DeviceRegistrationResult instance.
            // This result contains a number of properties including the DeviceId,
            // AssignedHub and the Status.
            var result = await provisioningDeviceClient
                         .RegisterAsync()
                         .ConfigureAwait(false);

            Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

            // The method then checks to ensure that the provisioning status has
            // been set and throws an exception if the device is not Assigned.
            // Other possible results here include Unassigned, Assigning,
            // Failed and Disabled.
            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'");
            }

            // The DeviceAuthenticationWithRegistrySymmetricKey class simplifies
            // the creation of an IoT Hub connection string using the device
            // ID and the Primary Symmetric Key
            var auth = new DeviceAuthenticationWithRegistrySymmetricKey(
                result.DeviceId,
                security.GetPrimaryKey());

            // Finally, a DeviceClient instance is returned that is connected
            // to the desired IoT Hub, using the authentication created above,
            // and using the AMQP protocol.
            return(DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp));
        }
Example #6
0
        protected virtual async Task <DeviceRegistrationResult> RegisterDeviceAsync(
            string dpsGlobalDeviceEndpoint,
            string dpsIdScope)
        {
            DeviceRegistrationResult result = null;

            using (var security =
                       new SecurityProviderX509Certificate(
                           this.HardwareSecurityModel.DeviceLeafCert))
                using (var transport =
                           new ProvisioningTransportHandlerMqtt(
                               TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(
                            dpsGlobalDeviceEndpoint,
                            dpsIdScope,
                            security,
                            transport);

                    result = await provClient.RegisterAsync().ConfigureAwait(false);
                }

            return(result);
        }
        public static async Task RunAsync(ProvisioningDeviceClient provisioningDeviceClient, SecurityProvider security)
        {
            Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}");

            Console.Write("ProvisioningClient RegisterAsync . . . ");
            DeviceRegistrationResult result = await provisioningDeviceClient.RegisterAsync().ConfigureAwait(false);

            Console.WriteLine($"{result.Status}");
            Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

            if (result.Status == ProvisioningRegistrationStatusType.Assigned)
            {
                X509Certificate2 certificate = (security as SecurityProviderX509).GetAuthenticationCertificate();
                Console.WriteLine($"Registration certificate thumbprint: {certificate.Thumbprint}");
                IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, certificate);
                using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp))
                {
                    Console.WriteLine("DeviceClient OpenAsync.");
                    await iotClient.OpenAsync().ConfigureAwait(false);

                    Console.WriteLine("DeviceClient SendEventAsync.");
                    await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                    Console.WriteLine("DeviceClient CloseAsync.");
                    await iotClient.CloseAsync().ConfigureAwait(false);
                }
            }
        }
Example #8
0
        public static async Task RunSample(X509Certificate2 certificate)
        {
            using (var security = new SecurityProviderX509Certificate(certificate))
                // using (var transport = new ProvisioningTransportHandlerHttp())
                //using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);

                    Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}");
                    Console.Write("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync();

                    Console.WriteLine($"{result.Status}");
                    Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        return;
                    }

                    IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, certificate);
                    iotClient = DeviceClient.Create(result.AssignedHub, auth);

                    Console.WriteLine($"Now {deviceID} can start sending messages to assigned IoT Hub: {result.AssignedHub}");

                    await iotClient.OpenAsync();

                    SendDeviceToCloudMessagesAsync();


                    Console.ReadLine();
                }
        }
        public DeviceRegistrationResult RegisterDevice(string deviceId, string password)
        {
            var cert = deviceManager.ReadPrivateCertificate(deviceId, password);

            using (var security = new SecurityProviderX509Certificate(cert))
            {
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(configuration.GetValue <string>("DeviceProvisioningEndpoint"), configuration.GetValue <string>("DeviceProvisioningScope"), security, transport);

                    var result = provClient.RegisterAsync().GetAwaiter().GetResult();

                    deviceManager.SaveRegistration(new Models.RegistrationInfo
                    {
                        AssignedHub    = result.AssignedHub,
                        DeviceId       = result.DeviceId,
                        RegistrationId = result.RegistrationId
                    });
                    deviceManager.SavePassword(deviceId, password);

                    return(result);
                }
            }
        }
Example #10
0
        static void Main(string[] args)
        {
            string[] certFilePaths     = Directory.GetFiles(ConfigurationManager.AppSettings["CertDirectory"], "*.pfx");
            string   plainTextPassword = ConfigurationManager.AppSettings["SecureString"];

            foreach (string certFilePath in certFilePaths)
            {
                using (X509Certificate2 cert = new X509Certificate2(certFilePath, plainTextPassword, X509KeyStorageFlags.UserKeySet))
                {
                    using (var security = new SecurityProviderX509Certificate(cert))
                        using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                        {
                            ProvisioningDeviceClient provClient =
                                ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, IdScope, security, transport);

                            Console.WriteLine($"Registering device with RegistrationID = {security.GetRegistrationID()}");
                            DeviceRegistrationResult result = provClient.RegisterAsync().GetAwaiter().GetResult();

                            Console.WriteLine($"{result.Status}");
                            Console.WriteLine(
                                $"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
                        }
                }
            }
        }
Example #11
0
        public async Task ProvisioningDeviceClient_InvalidRegistrationId_TpmRegister_Fail(string transportType)
        {
            if (!ConfigurationFound())
            {
                _log.WriteLine("Provisioning test configuration not found. Result inconclusive.");
                return;
            }

            using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, TransportFallbackType.TcpOnly))
                using (SecurityProvider security = new SecurityProviderTpmSimulator("invalidregistrationid"))
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                        s_globalDeviceEndpoint,
                        Configuration.Provisioning.IdScope,
                        security,
                        transport);

                    var cts = new CancellationTokenSource(FailingTimeoutMiliseconds);

                    _log.WriteLine("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false);

                    _log.WriteLine($"{result.Status}");

                    Assert.AreEqual(ProvisioningRegistrationStatusType.Failed, result.Status);
                    Assert.IsNull(result.AssignedHub);
                    Assert.IsNull(result.DeviceId);
                    Assert.AreEqual("Not Found", result.ErrorMessage);
                    Assert.AreEqual(0x00062ae9, result.ErrorCode);
                }
        }
Example #12
0
        // https://github.com/Azure-Samples/azure-iot-samples-csharp/blob/master/provisioning/Samples/device/SymmetricKeySample/Program.cs
        // Azure IoT Central Client

        static async Task Main(string[] args)
        {
            IAuthenticationMethod auth;

            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey))
                using (var transport = new ProvisioningTransportHandlerHttp())
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, idScope, security, transport);
                    DeviceRegistrationResult result     = await provClient.RegisterAsync();

                    auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (security as SecurityProviderSymmetricKey).GetPrimaryKey());

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt))
                    {
                        while (true)
                        {
                            if (_temperature.IsAvailable)
                            {
                                try
                                {
                                    Console.WriteLine($"The CPU temperature is {Math.Round(_temperature.Temperature.Celsius, 2)}");
                                    await SendMsgIotHub(iotClient, _temperature.Temperature.Celsius);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("exception msg: " + ex.Message);
                                }
                            }
                            Thread.Sleep(10000); // sleep for 10 seconds
                        }
                    }
                }
        }
        public async Task RunSampleAsync()
        {
            // When registering with a symmetric key using a group enrollment, the provided key will not
            // work for a specific device, rather it must be computed based on two values: the group enrollment
            // key and the desired device Id.
            if (_parameters.EnrollmentType == EnrollmentType.Group)
            {
                _parameters.PrimaryKey = ComputeDerivedSymmetricKey(_parameters.PrimaryKey, _parameters.Id);
            }

            Console.WriteLine($"Initializing the device provisioning client...");

            // For individual enrollments, the first parameter must be the registration Id, where in the enrollment
            // the device Id is already chosen. However, for group enrollments the device Id can be requested by
            // the device, as long as the key has been computed using that value.
            // Also, the secondary could could be included, but was left out for the simplicity of this sample.
            using var security = new SecurityProviderSymmetricKey(
                      _parameters.Id,
                      _parameters.PrimaryKey,
                      null);

            using var transportHandler = GetTransportHandler();

            ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                _parameters.GlobalDeviceEndpoint,
                _parameters.IdScope,
                security,
                transportHandler);

            Console.WriteLine($"Initialized for registration Id {security.GetRegistrationID()}.");

            Console.WriteLine("Registering with the device provisioning service...");
            DeviceRegistrationResult result = await provClient.RegisterAsync();

            Console.WriteLine($"Registration status: {result.Status}.");
            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                Console.WriteLine($"Registration status did not assign a hub, so exiting this sample.");
                return;
            }

            Console.WriteLine($"Device {result.DeviceId} registered to {result.AssignedHub}.");

            Console.WriteLine("Creating symmetric key authentication for IoT Hub...");
            IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(
                result.DeviceId,
                security.GetPrimaryKey());

            Console.WriteLine($"Testing the provisioned device with IoT Hub...");
            using DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, _parameters.TransportType);

            Console.WriteLine("Sending a telemetry message...");
            using var message = new Message(Encoding.UTF8.GetBytes("TestMessage"));
            await iotClient.SendEventAsync(message);

            Console.WriteLine("Finished.");
        }
Example #14
0
        public async Task RunSampleAsync()
        {
            try
            {
                Console.WriteLine($"RegistrationID = {_security.GetRegistrationID()}");
                VerifyRegistrationIdFormat(_security.GetRegistrationID());

                Console.Write("ProvisioningClient RegisterAsync . . . ");
                DeviceRegistrationResult result = await _provClient.RegisterAsync().ConfigureAwait(false);

                Console.WriteLine($"{result.Status}");
                Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                {
                    return;
                }

                Microsoft.Azure.Devices.Client.IAuthenticationMethod auth;
                if (_security is SecurityProviderTpm)
                {
                    Console.WriteLine("Creating TPM DeviceClient authentication.");
                    auth = new DeviceAuthenticationWithTpm(result.DeviceId, _security as SecurityProviderTpm);
                }
                else if (_security is SecurityProviderX509)
                {
                    Console.WriteLine("Creating X509 DeviceClient authentication.");
                    auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (_security as SecurityProviderX509).GetAuthenticationCertificate());
                }
                else if (_security is SecurityProviderSymmetricKey)
                {
                    Console.WriteLine("Creating Symmetric Key DeviceClient authenication");
                    auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (_security as SecurityProviderSymmetricKey).GetPrimaryKey());
                }
                else
                {
                    throw new NotSupportedException("Unknown authentication type.");
                }

                using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, Microsoft.Azure.Devices.Client.TransportType.Amqp))
                {
                    Console.WriteLine("DeviceClient OpenAsync.");
                    await iotClient.OpenAsync().ConfigureAwait(false);

                    Console.WriteLine("DeviceClient SendEventAsync.");
                    await iotClient.SendEventAsync(new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                    Console.WriteLine("DeviceClient CloseAsync.");
                    await iotClient.CloseAsync().ConfigureAwait(false);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #15
0
        public async Task <ResultCommand> ProvisionDevice(RequestCommandProvisionDevice requestProvisionDevice, string password)
        {
            try
            {
                DeviceCertificateModel certificateInfo = requestProvisionDevice.DeviceCertificateInformation;

                //Load certificate chain
                var(deviceCertificate, collectionCertificates) =
                    LoadCertificateFromPfx(Convert.FromBase64String(certificateInfo.Certificate), password);

                //Save certificate in store
                if (!await SaveCertificateInStore(deviceCertificate))
                {
                    return(ResultCommand.CreateFailedCommand($"Error while saving User Certificate in Store."));
                }

                using (var securityProvider = new SecurityProviderX509Certificate(deviceCertificate, collectionCertificates))
                {
                    using (var transport = new ProvisioningTransportHandlerHttp())
                    {
                        ProvisioningDeviceClient provClient =
                            ProvisioningDeviceClient.Create(certificateInfo.DpsInstance, certificateInfo.DpsIdScope, securityProvider, transport);
                        DeviceRegistrationResult result = await provClient.RegisterAsync();

                        if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                        {
                            DebugHelper.LogError($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
                            return(ResultCommand.CreateFailedCommand($"Error during registration: {result.Status}, {result.ErrorMessage}"));
                        }

                        //Test the connection
                        if (!await TestDeviceConnection(result.DeviceId, result.AssignedHub, deviceCertificate))
                        {
                            return(ResultCommand.CreateFailedCommand($"Error while testing the device connection."));
                        }

                        //Persist provision in TPM/HSM
                        SimulatedDevice.ProvisionDevice(result.AssignedHub, result.DeviceId);

                        //Provisioned!
                        SimulatedDevice.IsProvisioned = true;
                    }
                }
                if (deviceCertificate != null)
                {
                    deviceCertificate.Dispose();
                }

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error ProvisionDevice: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error ProvisionDevice: {e.Message}."));
            }
        }
Example #16
0
        static async Task <DeviceRegistrationResult> GetDeviceRegistrationResultAsync(ProvisioningDeviceClient provClient, SecurityProviderX509 security)
        {
            DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                throw new Exception("Device not assigned");
            }
            return(result);
        }
Example #17
0
        //Provision the Device
        static void ProvisionDevice()
        {
            Console.WriteLine("Provisioning process starting..");
            Console.WriteLine("Fetching secrets..");
            var secrets = ReadSecrets();

            if (secrets == null)
            {
                Console.WriteLine("No secrets found!");
                return;
            }

            Console.WriteLine("Secrets found!");

            string dpsServiceEndpoint = secrets.serviceEndpoint;
            string idScope            = secrets.idScope;
            string registrationId     = secrets.registrationId;
            string primaryDeviceKey   = secrets.primaryDerivedKey;
            string secondaryDeviceKey = secrets.secondaryDerivedKey;

            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryDeviceKey, secondaryDeviceKey))
            {
                // Select one of the available transports:
                // To optimize for size, reference only the protocols used by your application.
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerHttp())
                // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.WebSocketOnly))
                {
                    try
                    {
                        Console.WriteLine("Creating provisioning client");

                        ProvisioningDeviceClient provClient =
                            ProvisioningDeviceClient.Create(dpsServiceEndpoint, idScope, security, transport);

                        Console.WriteLine("Starting attestation..");
                        DeviceRegistrationResult registrationResult = provClient.RegisterAsync().GetAwaiter().GetResult();
                        Console.WriteLine("Device successfully provisioned");

                        Console.WriteLine("Storing primary and secondary connection strings in settings file!");
                        Console.WriteLine("Primary Connection string: Hostname={0};DeviceId={1};SharedAccessKey={2}", registrationResult.AssignedHub, registrationId, primaryDeviceKey);
                        Console.WriteLine("Secondary Connection string: Hostname={0};DeviceId={1};SharedAccessKey={2}", registrationResult.AssignedHub, registrationId, secondaryDeviceKey);
                        string primaryConnectionString   = "Hostname=" + registrationResult.AssignedHub + ";DeviceId=" + registrationResult.DeviceId + ";SharedAccessKey=" + primaryDeviceKey;
                        string secondaryConnectionString = "Hostname=" + registrationResult.AssignedHub + ";DeviceId=" + registrationResult.DeviceId + ";SharedAccessKey=" + secondaryDeviceKey;

                        WriteSettings(primaryConnectionString, secondaryConnectionString);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message + ": " + ex.InnerException.Message);
                    }
                }
            }
        }
Example #18
0
        public static async Task RunSample()
        {
            // Replace the following type with SecurityClientTpm() to use a real TPM2.0 device.
            Console.WriteLine("Starting TPM simulator.");
            SecurityClientTpmSimulator.StartSimulatorProcess();

            using (var security = new SecurityClientTpmSimulator(RegistrationId))
                using (var transport = new ProvisioningTransportHandlerHttp())
                {
                    // Note that the TPM simulator will create a NVChip file containing the simulated TPM state.
                    Console.WriteLine("Extracting endorsement key.");
                    string base64EK = Convert.ToBase64String(security.GetEndorsementKey());

                    Console.WriteLine(
                        "In your Azure Device Provisioning Service please go to 'Manage enrollments' and select " +
                        "'Individual Enrollments'. Select 'Add' then fill in the following:");

                    Console.WriteLine("\tMechanism: TPM");
                    Console.WriteLine($"\tRegistration ID: {RegistrationId}");
                    Console.WriteLine($"\tEndorsement key: {base64EK}");
                    Console.WriteLine("\tDevice ID: iothubtpmdevice1 (or any other valid DeviceID)");
                    Console.WriteLine();
                    Console.WriteLine("Press ENTER when ready.");
                    Console.ReadLine();

                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(s_idScope, security, transport);

                    Console.Write("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync();

                    Console.WriteLine($"{result.Status}");
                    Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        return;
                    }

                    var auth = new DeviceAuthenticationWithTpm(result.DeviceId, security);
                    // TODO: Temporary workaround until IoTHub DeviceClient gets Token refresh support.
                    await auth.GetTokenAsync(result.AssignedHub);

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt))
                    {
                        Console.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync();

                        Console.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage")));

                        Console.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync();
                    }
                }
        }
Example #19
0
        public async Task ProvisioningDeviceClient_ValidRegistrationId_Register_Ok(
            string transportType,
            string securityType,
            X509EnrollmentType?x509EnrollmentType,
            TransportFallbackType?transportFallback,
            bool setCustomProxy,
            string proxyServerAddress = null)
        {
            using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, transportFallback))
                using (SecurityProvider security = await CreateSecurityProviderFromName(securityType, x509EnrollmentType).ConfigureAwait(false))
                {
                    _verboseLog.WriteLine("Creating device");

                    if (ImplementsWebProxy(transportType, transportFallback) && setCustomProxy)
                    {
                        transport.Proxy = (proxyServerAddress != null) ? new WebProxy(proxyServerAddress) : null;
                    }

                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                        s_globalDeviceEndpoint,
                        Configuration.Provisioning.IdScope,
                        security,
                        transport);

                    var cts = new CancellationTokenSource(PassingTimeoutMiliseconds);

                    _log.WriteLine("ProvisioningDeviceClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false);

                    Assert.IsNotNull(result);
                    _log.WriteLine($"{result.Status} (Error Code: {result.ErrorCode}; Error Message: {result.ErrorMessage})");
                    _log.WriteLine($"ProvisioningDeviceClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    Assert.AreEqual(ProvisioningRegistrationStatusType.Assigned, result.Status);
                    Assert.IsNotNull(result.AssignedHub);
                    Assert.IsNotNull(result.DeviceId);

                    Client.IAuthenticationMethod auth = CreateAuthenticationMethodFromSecurityProvider(security, result.DeviceId);

                    // TODO: #591 - ProvisioningClient and DeviceClient should use the same protocol.
                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, Client.TransportType.Http1))
                    {
                        _log.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync().ConfigureAwait(false);

                        _log.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(
                            new Client.Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                        _log.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync().ConfigureAwait(false);
                    }
                }
        }
Example #20
0
        private static async Task TestInvalidServiceCertificate(ProvisioningTransportHandler transport)
        {
            using var security =
                      new SecurityProviderX509Certificate(Configuration.Provisioning.GetIndividualEnrollmentCertificate());
            ProvisioningDeviceClient provisioningDeviceClient = ProvisioningDeviceClient.Create(
                Configuration.Provisioning.GlobalDeviceEndpointInvalidServiceCertificate,
                "0ne00000001",
                security,
                transport);

            await provisioningDeviceClient.RegisterAsync().ConfigureAwait(false);
        }
        public async Task RunAsync()
        {
            Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}");

            // Register the Device with DPS
            Console.Write("ProvisioningClient RegisterAsync . . . ");
            DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

            Console.WriteLine($"Device Registration Status: {result.Status}");
            Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
            deviceId = result.DeviceId;

            // Verify Device Registration Status
            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'");
            }

            // Create x509 DeviceClient Authentication
            Console.WriteLine("Creating X509 DeviceClient authentication.");
            var auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (security as SecurityProviderX509).GetAuthenticationCertificate());


            Console.WriteLine("Simulated Device. Ctrl-C to exit.");
            using (iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp))
            {
                // Explicitly open DeviceClient to communicate with Azure IoT Hub
                Console.WriteLine("DeviceClient OpenAsync.");
                await iotClient.OpenAsync().ConfigureAwait(false);


                // TODO 1: Setup OnDesiredPropertyChanged Event Handling to receive Desired Properties changes
                Console.WriteLine("Connecting SetDesiredPropertyUpdateCallbackAsync event handler...");
                await iotClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false);


                // TODO 2: Load Device Twin Properties since device is just starting up
                Console.WriteLine("Loading Device Twin Properties...");
                var twin = await iotClient.GetTwinAsync().ConfigureAwait(false);

                // Use OnDesiredPropertyChanged event handler to set the loaded Device Twin Properties (re-use!)
                await OnDesiredPropertyChanged(twin.Properties.Desired, null);


                // Start reading and sending device telemetry
                Console.WriteLine("Start reading and sending device telemetry...");
                await SendDeviceToCloudMessagesAsync(iotClient);

                // Explicitly close DeviceClient
                Console.WriteLine("DeviceClient CloseAsync.");
                await iotClient.CloseAsync().ConfigureAwait(false);
            }
        }
Example #22
0
        static async Task <DeviceClient> DeviceRegistration(string applicationId, string deviceId, int port)
        {
            string deviceKey;

            // See if AzureIoT hub connections string has been configured
            string connectionString = ApplicationConfiguration.ConnectionStringResolve(applicationId, port);

            if (!String.IsNullOrEmpty(connectionString))
            {
                return(DeviceClient.CreateFromConnectionString(connectionString, deviceId));
            }

            // See if Azure DPS has been configured
            using (var hmac = new HMACSHA256(Convert.FromBase64String(ApplicationConfiguration.DpsEnrollmentGroupSymmetricKeyResolve(applicationId, port))))
            {
                deviceKey = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(deviceId)));
            }

            using (var securityProvider = new SecurityProviderSymmetricKey(deviceId, deviceKey, null))
            {
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(ApplicationConfiguration.DpsGlobaDeviceEndpointResolve(),
                                                                                          ApplicationConfiguration.DpsIdScopeResolve(applicationId, port),
                                                                                          securityProvider,
                                                                                          transport);

                    DeviceRegistrationResult result = await provClient.RegisterAsync();

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        throw new ApplicationException($"DevID:{deviceId} Status:{result.Status} RegisterAsync failed");
                    }

                    IAuthenticationMethod authentication = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (securityProvider as SecurityProviderSymmetricKey).GetPrimaryKey());

                    return(DeviceClient.Create(result.AssignedHub,
                                               authentication,
                                               new ITransportSettings[]
                    {
                        new AmqpTransportSettings(TransportType.Amqp_Tcp_Only)
                        {
                            PrefetchCount = 0,
                            AmqpConnectionPoolSettings = new AmqpConnectionPoolSettings()
                            {
                                Pooling = true,
                            }
                        }
                    }
                                               ));
                }
            }
        }
Example #23
0
        public async Task <Microsoft.Azure.Devices.Client.DeviceClient> ProvisionAsync <DeviceClient>(DataStorage storage)
        {
            var connStringContent       = storage.Read("ConnectionString");
            DevicePortalInfoModel model = JsonConvert.DeserializeObject <DevicePortalInfoModel>(connStringContent);
            string scope          = model.Device.ID_Scope;
            string primaryKey     = model.Device.PrimaryKey;
            string secondaryKey   = model.Device.SecondaryKey;
            string registrationId = model.Device.RegistrationId;

            _sendTelemetry = false;

            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey))
            {
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    _sendTelemetry = false;
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, scope, security, transport);
                    DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        return(null);
                    }
                    Console.WriteLine($"Provisioninged device : {result.DeviceId} at {result.AssignedHub}");
                    var client = Microsoft.Azure.Devices.Client.DeviceClient.Create(result.AssignedHub, model.Auth, TransportType.Amqp);
                    client.SetMethodHandlerAsync("Reprovision", ReprovisionHandler, null).GetAwaiter().GetResult();
                    client.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdated, null).GetAwaiter().GetResult();

                    //  TODO:Save new connection information
                    var auth    = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, security.GetPrimaryKey());
                    var host    = result.AssignedHub;
                    var builder = IotHubConnectionStringBuilder.Create(host, auth);
                    var device  = new DevicePortalInfoModel
                    {
                        Host   = result.AssignedHub,
                        Auth   = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, security.GetPrimaryKey()),
                        Device = new DeviceModel {
                            ID_Scope       = scope,
                            PrimaryKey     = security.GetPrimaryKey(),
                            SecondaryKey   = security.GetSecondaryKey(),
                            RegistrationId = result.RegistrationId,
                            DeviceId       = result.DeviceId
                        },
                        ConnectionString = builder.ToString()
                    };

                    _storage.Write(DataStorage.DeviceConnectionString, JsonConvert.SerializeObject(device));
                    return(client);
                }
            }
        }
Example #24
0
        public async Task ProvisioningDeviceClient_ValidRegistrationId_Register_Ok(
            string transportType,
            string securityType,
            X509EnrollmentType?x509EnrollmentType,
            TransportFallbackType?transportFallback)
        {
            if (!ConfigurationFound())
            {
                _log.WriteLine("Provisioning test configuration not found. Result inconclusive.");
                return;
            }

            using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, transportFallback))
                using (SecurityProvider security = CreateSecurityProviderFromName(securityType, x509EnrollmentType))
                {
                    _verboseLog.WriteLine("Creating device");

                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                        s_globalDeviceEndpoint,
                        Configuration.Provisioning.IdScope,
                        security,
                        transport);

                    var cts = new CancellationTokenSource(PassingTimeoutMiliseconds);

                    _log.WriteLine("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false);

                    Assert.IsNotNull(result);
                    _log.WriteLine($"{result.Status} (Error Code: {result.ErrorCode}; Error Message: {result.ErrorMessage})");
                    _log.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    Assert.AreEqual(ProvisioningRegistrationStatusType.Assigned, result.Status);
                    Assert.IsNotNull(result.AssignedHub);
                    Assert.IsNotNull(result.DeviceId);

                    Client.IAuthenticationMethod auth = CreateAuthenticationMethodFromSecurityProvider(security, result.DeviceId);

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, Client.TransportType.Mqtt_Tcp_Only))
                    {
                        _log.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync().ConfigureAwait(false);

                        _log.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(
                            new Client.Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                        _log.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync().ConfigureAwait(false);
                    }
                }
        }
Example #25
0
        // Provision a device via DPS, by sending the PnP model Id as DPS payload.
        private static async Task <DeviceRegistrationResult> ProvisionDeviceAsync(Parameters parameters, CancellationToken cancellationToken)
        {
            SecurityProvider             symmetricKeyProvider = new SecurityProviderSymmetricKey(parameters.DeviceId, parameters.DeviceSymmetricKey, null);
            ProvisioningTransportHandler mqttTransportHandler = new ProvisioningTransportHandlerMqtt();
            ProvisioningDeviceClient     pdc = ProvisioningDeviceClient.Create(parameters.DpsEndpoint, parameters.DpsIdScope, symmetricKeyProvider, mqttTransportHandler);

            var pnpPayload = new ProvisioningRegistrationAdditionalData
            {
                JsonData = PnpConvention.CreateDpsPayload(ModelId),
            };

            return(await pdc.RegisterAsync(pnpPayload, cancellationToken));
        }
        static async Task Main(string[] args)
        {
            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey))
                using (var transport = new ProvisioningTransportHandlerMqtt())
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, idScope, security, transport);
                    var pnpPayload = new ProvisioningRegistrationAdditionalData
                    {
                        JsonData = $"{{ \"modelId\": \"{ModelId}\" }}",
                    };

                    DeviceRegistrationResult result = await provClient.RegisterAsync(pnpPayload);

                    IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (security as SecurityProviderSymmetricKey).GetPrimaryKey());

                    using (iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt))
                    {
                        await iotClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChangedAsync, null).ConfigureAwait(false); // callback for Device Twin updates
                        await DeviceTwinGetInitialState(iotClient);                                                                       // Get current cloud state of the device twin

                        while (true)
                        {
                            if (_temperature.IsAvailable)
                            {
                                try
                                {
                                    temperature = Math.Round(_temperature.Temperature.DegreesCelsius, 2);

                                    Console.WriteLine($"The CPU temperature is {temperature}");

                                    await SendMsgIotHub(iotClient, temperature);

                                    roomState = (int)temperature > targetTemperature ? RoomAction.Cooling : (int)temperature < targetTemperature ? RoomAction.Heating : RoomAction.Green;
                                    await UpdateRoomAction(roomState);

                                    if (temperature > maxTemperature)
                                    {
                                        maxTemperature = temperature;
                                        await UpdateDeviceTwin("maxTempSinceLastReboot", maxTemperature);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("exception msg: " + ex.Message);
                                }
                            }
                            Thread.Sleep(2000); // sleep for 2 seconds
                        }
                    }
                }
        }
Example #27
0
        public async Task RunAsync()
        {
            colorMessage($"\nRegistrationID = {_security.GetRegistrationID()}", ConsoleColor.Yellow);

            // Register the Device with DPS.
            whiteMessage("ProvisioningClient RegisterAsync . . . ");
            DeviceRegistrationResult result = await _provClient.RegisterAsync().ConfigureAwait(false);

            if (result.Status == ProvisioningRegistrationStatusType.Assigned)
            {
                greenMessage($"Device Registration Status: {result.Status}");
                greenMessage($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
            }
            else
            {
                redMessage($"Device Registration Status: {result.Status}");
                throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'");
            }

            // Create x509 DeviceClient Authentication.
            whiteMessage("Creating X509 DeviceClient authentication.");
            var auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (_security as SecurityProviderX509).GetAuthenticationCertificate());

            whiteMessage("Simulated Device. Ctrl-C to exit.");
            using (s_deviceClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp))
            {
                // Explicitly open DeviceClient to communicate with Azure IoT Hub.
                whiteMessage("DeviceClient OpenAsync.");
                await s_deviceClient.OpenAsync().ConfigureAwait(false);

                // Setup OnDesiredPropertyChanged Event Handling to receive Desired Properties changes.
                whiteMessage("Connecting SetDesiredPropertyUpdateCallbackAsync event handler...");
                await s_deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false);

                // Load Device Twin Properties since device is just starting up.
                whiteMessage("Loading Device Twin Properties...");
                var twin = await s_deviceClient.GetTwinAsync().ConfigureAwait(false);

                // Use OnDesiredPropertyChanged event handler to set the loaded Device Twin properties.
                await OnDesiredPropertyChanged(twin.Properties.Desired, null);

                // Start reading and sending device telemetry.
                colorMessage("\nStart reading and sending device telemetry...\n", ConsoleColor.Yellow);
                await SendDeviceToCloudMessagesAsync2(s_deviceClient);

                // Explicitly close DeviceClient.
                whiteMessage("DeviceClient CloseAsync.");
                await s_deviceClient.CloseAsync().ConfigureAwait(false);
            }
        }
Example #28
0
        /// <summary>
        /// Registers device with IoT Hub using Device Provisioning Service
        /// </summary>
        /// <param name="cert"></param>
        /// <param name="s_idScope"></param>
        /// <returns></returns>
        public async Task <DeviceRegistrationResult> RegisterDevice(X509Certificate2 cert, string s_idScope)
        {
            using (var security = new SecurityProviderX509Certificate(cert))
                // using (var transport = new ProvisioningTransportHandlerHttp())
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);
                    DeviceRegistrationResult result = await provClient.RegisterAsync();

                    return(result);
                }
        }
Example #29
0
        private async Task <DeviceRegistrationResult> RegisterAsync(SecurityProvider security, CancellationToken token)
        {
            _Logger.EnteringMethodAzure(nameof(CommunicationContext));
            ProvisioningTransportHandler transport = null;

            try
            {
                switch (_azureDeviceParameters.TransportType)
                {
                case TransportType.Amqp:
                    transport = new ProvisioningTransportHandlerAmqp();
                    break;

                case TransportType.Http1:
                    transport = new ProvisioningTransportHandlerHttp();
                    break;

                case TransportType.Amqp_WebSocket_Only:
                    transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.WebSocketOnly);
                    break;

                case TransportType.Amqp_Tcp_Only:
                    transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly);
                    break;

                case TransportType.Mqtt:
                    transport = new ProvisioningTransportHandlerMqtt();
                    break;

                case TransportType.Mqtt_WebSocket_Only:
                    transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.WebSocketOnly);
                    break;

                case TransportType.Mqtt_Tcp_Only:
                    transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                ProvisioningDeviceClient provisioningClient = ProvisioningDeviceClient.Create(_globalDeviceEndpoint, _azureDeviceParameters.AzureScopeId, security, transport);
                _Logger.EnteringMethodAzure(nameof(ProvisioningDeviceClient), nameof(ProvisioningDeviceClient.RegisterAsync));
                return(await provisioningClient.RegisterAsync(token));
            }
            finally
            {
                _Logger.EnteringMethodAzure(nameof(ProvisioningTransportHandler), nameof(ProvisioningTransportHandler.Dispose));
                transport.Dispose();
            }
        }
Example #30
0
        static async Task <EnrollmentDetails> EnrollDeviceAsync(string deviceId)
        {
            //we need a couple of parameters to start. How you get these values is up to you.
            //What is important is that the enrollment keys (Primary & secondary) should
            //be considered as secrets and stored as such. Just like certificate, it
            //will be the responsibility of Bell to deploy these credentials to the device
            //and keep them up to date
            string dpsEndpoint            = Environment.GetEnvironmentVariable("dpsEndpoint") ?? "global.azure-devices-provisioning.net";
            string dpsIdScope             = Environment.GetEnvironmentVariable("idscope") ?? "{Insert ID Scope Here}";
            string enrollmentKeyPrimary   = Environment.GetEnvironmentVariable("enrollmentKeyPrimary") ?? "{Insert Primary Enrollment Key Here}";
            string enrollmentKeySecondary = Environment.GetEnvironmentVariable("enrollmentKeySecondary") ?? "{Insert Seconday Enrollment Key Here}";

            //first, we need to create a device specific attestation key, derived from
            //the enrollment key. These attestation keys will ultimately become the credentials
            //for the device into Iot Hub when provisioned. They also serve as a way for
            //the DPS service to validate the device is trusted, without actually having to
            //send the enrollment group key across the network
            string attestationKeyPrimary   = ComputeDeviceAttestationKey(enrollmentKeyPrimary, deviceId);
            string attestationKeySecondary = ComputeDeviceAttestationKey(enrollmentKeySecondary, deviceId);

            //now, we can attempt to register this device with DPS
            using (SecurityProviderSymmetricKey keyProvider = new SecurityProviderSymmetricKey(deviceId, attestationKeyPrimary, attestationKeySecondary))
            {
                using (ProvisioningTransportHandlerAmqp transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provisioningClient = ProvisioningDeviceClient.Create(dpsEndpoint, dpsIdScope, keyProvider, transport);
                    DeviceRegistrationResult result             = await provisioningClient.RegisterAsync();

                    switch (result.Status)
                    {
                    case ProvisioningRegistrationStatusType.Assigned:
                        //device was successfully assigned by dps to an Iot Hub
                        return(new EnrollmentDetails()
                        {
                            DeviceId = deviceId,
                            IotHubEndpoint = result.AssignedHub,
                            Authentication = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, attestationKeyPrimary)
                        });

                    case ProvisioningRegistrationStatusType.Assigning:
                    case ProvisioningRegistrationStatusType.Disabled:
                    case ProvisioningRegistrationStatusType.Failed:
                    case ProvisioningRegistrationStatusType.Unassigned:
                    default:
                        return(null);
                    }
                }
            }
        }