private void ConnectViaDPSX509(SecureString password, TransportType transportType) { string certPath = Environment.GetEnvironmentVariable("DEVICE_CERTIFICATE"); if (certPath == null) { certPath = ConfigurationManager.AppSettings["DEVICE_CERTIFICATE"]; } string scopeId = Environment.GetEnvironmentVariable("DPS_IDSCOPE"); if (scopeId == null) { scopeId = ConfigurationManager.AppSettings["DPS_IDSCOPE"]; } System.Security.Cryptography.X509Certificates.X509Certificate2 myCert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certPath, password); using (var security = new SecurityProviderX509Certificate(myCert)) { using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly)) // using (var transport = new ProvisioningTransportHandlerHttp()) // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly)) // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.WebSocketOnly)) { ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, scopeId, security, transport); Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}"); VerifyRegistrationIdFormat(security.GetRegistrationID()); Console.Write("ProvisioningClient RegisterAsync . . . "); DeviceRegistrationResult result = provClient.RegisterAsync().Result; deviceId = result.DeviceId; Console.WriteLine($"{result.Status}"); Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}"); if (result.Status != ProvisioningRegistrationStatusType.Assigned) { return; } var auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (security as SecurityProviderX509).GetAuthenticationCertificate()); deviceClient = DeviceClient.Create(result.AssignedHub, auth, transportType); } } }
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(); } }
private void ConnectViaX509(SecureString password, ClientType clientType, TransportType transportType) { string certPath = Environment.GetEnvironmentVariable("DEVICE_CERTIFICATE"); if (certPath == null) { certPath = ConfigurationManager.AppSettings["DEVICE_CERTIFICATE"]; } string iotHubUri = Environment.GetEnvironmentVariable("IOT_HUB_URI"); if (iotHubUri == null) { iotHubUri = ConfigurationManager.AppSettings["IOT_HUB_URI"]; } System.Security.Cryptography.X509Certificates.X509Certificate2 myCert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certPath, password); using (var security = new SecurityProviderX509Certificate(myCert)) { deviceId = security.GetRegistrationID(); // Device Client Type switch (clientType) { case ClientType.Primary: deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithX509Certificate(security.GetRegistrationID(), myCert), transportType); break; case ClientType.Secondary: secondaryDeviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithX509Certificate(security.GetRegistrationID(), myCert), transportType); break; } } }
public static async Task RunSample(X509Certificate2 certificate) { using (var security = new SecurityProviderX509Certificate(certificate)) using (var transport = new ProvisioningTransportHandlerAmqp(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); 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(); } } }
public async Task RunSampleAsync() { Console.WriteLine($"Loading the certificate..."); using X509Certificate2 certificate = LoadProvisioningCertificate(); using var security = new SecurityProviderX509Certificate(certificate); Console.WriteLine($"Initializing the device provisioning client..."); using var transport = GetTransportHandler(); ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( _parameters.GlobalDeviceEndpoint, _parameters.IdScope, security, transport); 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 X509 authentication for IoT Hub..."); IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate( result.DeviceId, certificate); 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); await iotClient.CloseAsync(); Console.WriteLine("Finished."); }
/// <summary> /// Provision device using DPS and send telemetry to IoT Hub. /// </summary> /// <returns></returns> public static async Task RunSampleAsync() { try { using var security = new SecurityProviderX509Certificate(certificate); Console.WriteLine($"Initializing the device provisioning client..."); // Use HTTP, AMQP or MQTT to communicate with DPS //var transportHandler = new ProvisioningTransportHandlerHttp(); //var transportHandler = new ProvisioningTransportHandlerAmqp(); var transportHandler = new ProvisioningTransportHandlerMqtt(); // Standard DPS provisioning flow using x.509 ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( dpsEndpoint, 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}."); // Standard IoT Hub authentication and connection flow using x.509 Console.WriteLine("Creating X509 authentication for IoT Hub..."); IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate( result.DeviceId, certificate); Console.WriteLine($"Connecting to IoT Hub..."); iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt); Console.WriteLine("Sending telemetry messages..."); var message = new Message(Encoding.UTF8.GetBytes("TestMessage")); for (int count = 0; count < MESSAGE_COUNT; count++) { await iotClient.SendEventAsync(message); Console.WriteLine($"Sent message {count}"); await Task.Delay(DELAY_BETWEEN_SENDS); } await iotClient.CloseAsync(); iotClient.Dispose(); Console.WriteLine("Finished."); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public async Task <string> ProvisionDevice() { string result = string.Empty; string logPrefix = "DPSProvisioningService.ProvisionDevice".BuildLogPrefix(); // 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 (_dpsSettings.EnrollmentType == EnrollmentType.Group) { if (_dpsSettings.GroupEnrollment == null) { throw new ArgumentNullException("_dpsSettings.GroupEnrollment", "No group enrollment settings have been found."); } if (_dpsSettings.GroupEnrollment.SecurityType == SecurityType.X509CA && _dpsSettings.GroupEnrollment.CAX509Settings != null) { string deviceCertificateFullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _dpsSettings.GroupEnrollment.CAX509Settings.DeviceX509Path); // X509 device leaf certificate string parameterDeviceId = _deviceSettingsDelegate.CurrentValue.ArtifactId; X509Certificate2 deviceLeafProvisioningCertificate = new X509Certificate2(deviceCertificateFullPath, _dpsSettings.GroupEnrollment.CAX509Settings.Password); _deviceSettingsDelegate.CurrentValue.DeviceId = deviceLeafProvisioningCertificate.Subject.Remove(0, 3); //delete the 'CN=' if (parameterDeviceId != _deviceSettingsDelegate.CurrentValue.DeviceId) { _logger.LogWarning($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::The leaf certificate has been created for the device '{_deviceSettingsDelegate.CurrentValue.DeviceId}' but the provided deviceId through the settings is '{parameterDeviceId}'. Provisioning will be executed with the deviceId included in the certificate."); } _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Initializing the device provisioning client..."); using (var security = new SecurityProviderX509Certificate(deviceLeafProvisioningCertificate)) { using (var transportHandler = ProvisioningTools.GetTransportHandler(_dpsSettings.GroupEnrollment.CAX509Settings.TransportType)) { ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( _dpsSettings.GroupEnrollment.CAX509Settings.GlobalDeviceEndpoint, _dpsSettings.GroupEnrollment.CAX509Settings.IdScope, security, transportHandler); _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Initialized for registration Id {security.GetRegistrationID()}."); _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Registering with the device provisioning service..."); DeviceRegistrationResult deviceRegistrationResult = await provClient.RegisterAsync(); if (deviceRegistrationResult != null) { _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Registration status: {deviceRegistrationResult.Status}."); if (deviceRegistrationResult.Status != ProvisioningRegistrationStatusType.Assigned) { _logger.LogWarning($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Device registration process did not assign an IoT Hub."); } else { _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Device {deviceRegistrationResult.DeviceId} registered to {deviceRegistrationResult.AssignedHub}."); _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Creating X509 leaf authentication for IoT Hub..."); _deviceSettingsDelegate.CurrentValue.DeviceId = deviceRegistrationResult.DeviceId; //HostName =< host_name >; DeviceId =< device_id >; x509 = true result = $"HostName={deviceRegistrationResult.AssignedHub};DeviceId={deviceRegistrationResult.DeviceId};x509=true"; } } else { _logger.LogError($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::No provisioning result has been received."); } } } } else { _logger.LogError($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::No X509 settings have been found."); } } return(result); }
private DeviceClient CreateModuleClientAsync(TransportType transportType) { var cert = DeviceAuthWithX509Certificate(certificate, password); using (var security = new SecurityProviderX509Certificate(cert)) { IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(security.GetRegistrationID(), (security as SecurityProviderX509).GetAuthenticationCertificate()); DeviceClient client = null; try { ITransportSettings[] settings = new ITransportSettings[] { new MqttTransportSettings(transportType) }; DeviceClient deviceClient = DeviceClient.Create(hostName, auth, settings); client = deviceClient; } catch (Exception ex) { Console.WriteLine(ex.Message); } return(client); } }
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}"); } } } }