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(); } } }
// This function create a device with x509 cert and connect to the iothub on the transport specified. // Then a message is send from the service client. // It then verifies the message is received on the device. private async Task ReceiveSingleMessageX509(Client.TransportType transport) { Tuple <string, string> deviceInfo = TestUtil.CreateDeviceWithX509(DevicePrefix, hostName, registryManager); ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(hubConnectionString); string certBase64 = Environment.GetEnvironmentVariable("IOTHUB_X509_PFX_CERTIFICATE"); Byte[] buff = Convert.FromBase64String(certBase64); var cert = new X509Certificate2(buff); var auth = new DeviceAuthenticationWithX509Certificate(deviceInfo.Item1, cert); var deviceClient = DeviceClient.Create(deviceInfo.Item2, auth, transport); await deviceClient.OpenAsync(); if (transport == Client.TransportType.Mqtt_Tcp_Only || transport == Client.TransportType.Mqtt_WebSocket_Only) { // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client. await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2)); } string payload, messageId, p1Value; await serviceClient.OpenAsync(); await serviceClient.SendAsync(deviceInfo.Item1, ComposeC2DTestMessage(out payload, out messageId, out p1Value)); await VerifyReceivedC2DMessage(transport, deviceClient, payload, p1Value); await deviceClient.CloseAsync(); await serviceClient.CloseAsync(); TestUtil.RemoveDevice(deviceInfo.Item1, registryManager); }
// init device. Create device config if does not exist. // If device config does not exist, device id is not known, so we attempt to read device.cer to determine it. // If device.cer is not found, we try to create it with new guid // or should we then look device id up by thumbprint? private static async void InitDevice() { JObject jobj = LoadConfig(configFile); if (jobj == null || registerDevice) { jobj = RegisterDevice(); SaveConfig(jobj); } // Create device and connect IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(deviceId, deviceCert); deviceClient = DeviceClient.Create(deviceIotHub, auth); deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).Wait(); try { await deviceClient.OpenAsync(); await deviceClient.UpdateReportedPropertiesAsync(deviceTwinProperties); } catch (Exception ex) { throw ex; } }
private async Task GetSasUriAsync(Client.TransportType transport, string blobName, bool x509auth = false) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync( Logger, _devicePrefix, x509auth?TestDeviceType.X509 : TestDeviceType.Sasl).ConfigureAwait(false); DeviceClient deviceClient; if (x509auth) { X509Certificate2 cert = Configuration.IoTHub.GetCertificateWithPrivateKey(); var auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert); deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, auth, transport); } else { deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); } using (deviceClient) { FileUploadSasUriResponse sasUriResponse = await deviceClient.GetFileUploadSasUriAsync(new FileUploadSasUriRequest { BlobName = blobName }); await deviceClient.CloseAsync().ConfigureAwait(false); } }
private static async Task <TestDevice> CreateDeviceAsync(TestDeviceType type, string prefix) { string deviceName = "E2E_" + prefix + Guid.NewGuid(); // Delete existing devices named this way and create a new one. using var rm = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString); _logger.Trace($"{nameof(GetTestDeviceAsync)}: Creating device {deviceName} with type {type}."); Client.IAuthenticationMethod auth = null; var requestDevice = new Device(deviceName); if (type == TestDeviceType.X509) { requestDevice.Authentication = new AuthenticationMechanism { X509Thumbprint = new X509Thumbprint { PrimaryThumbprint = Configuration.IoTHub.GetCertificateWithPrivateKey().Thumbprint } }; auth = new DeviceAuthenticationWithX509Certificate(deviceName, Configuration.IoTHub.GetCertificateWithPrivateKey()); } Device device = await rm.AddDeviceAsync(requestDevice).ConfigureAwait(false); _logger.Trace($"{nameof(GetTestDeviceAsync)}: Pausing for {DelayAfterDeviceCreationSeconds}s after device was created."); await Task.Delay(DelayAfterDeviceCreationSeconds * 1000).ConfigureAwait(false); await rm.CloseAsync().ConfigureAwait(false); return(new TestDevice(device, auth)); }
private static IAuthenticationMethod GetAuthenticationMethod(DeviceRegistrationResult result, SecurityProvider security) { 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."); } return(auth); }
public async Task X509_Cert_Chain_Install_Test_AMQP_TCP() { // arrange var chainCerts = new X509Certificate2Collection(); chainCerts.Add(Configuration.IoTHub.GetRootCACertificate()); chainCerts.Add(Configuration.IoTHub.GetIntermediate1Certificate()); chainCerts.Add(Configuration.IoTHub.GetIntermediate2Certificate()); var auth = new DeviceAuthenticationWithX509Certificate( Configuration.IoTHub.X509ChainDeviceName, Configuration.IoTHub.GetChainDeviceCertificateWithPrivateKey(), chainCerts); using var deviceClient = DeviceClient.Create( _hostName, auth, DeviceTransportType.Amqp_Tcp_Only); // act await deviceClient.OpenAsync().ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); // assert ValidateCertsAreInstalled(chainCerts); }
/// <summary> /// A sample to illustrate authenticating with a device by passing in the device certificate and /// full chain of certificates from the one used to sign the device certificate to the one uploaded to the service. /// AuthSetup.ps1 can be used to create the necessary certs and setup to run this sample. /// </summary> /// <param name="args"> /// Run with `--help` to see a list of required and optional parameters. /// </param> public static async Task <int> Main(string[] args) { // Parse application parameters Parameters parameters = null; ParserResult <Parameters> result = Parser.Default.ParseArguments <Parameters>(args) .WithParsed(parsedParams => { parameters = parsedParams; }) .WithNotParsed(errors => { Environment.Exit(1); }); var chainCerts = new X509Certificate2Collection(); chainCerts.Add(new X509Certificate2(parameters.RootCertPath)); chainCerts.Add(new X509Certificate2(parameters.Intermediate1CertPath)); chainCerts.Add(new X509Certificate2(parameters.Intermediate2CertPath)); var deviceCert = new X509Certificate2(parameters.DevicePfxPath, parameters.DevicePfxPassword); var auth = new DeviceAuthenticationWithX509Certificate(parameters.DeviceName, deviceCert, chainCerts); using var deviceClient = DeviceClient.Create( parameters.HostName, auth, parameters.TransportType); var sample = new X509DeviceCertWithChainSample(deviceClient); await sample.RunSampleAsync(); await deviceClient.CloseAsync(); return(0); }
private async Task X509InvalidDeviceIdOpenAsyncTwiceTest(Client.TransportType transportType) { string deviceName = $"DEVICE_NOT_EXIST_{Guid.NewGuid()}"; using var auth = new DeviceAuthenticationWithX509Certificate(deviceName, s_selfSignedCertificateWithPrivateKey); using var deviceClient = DeviceClient.Create(_hostName, auth, transportType); for (int i = 0; i < 2; i++) { try { await deviceClient.OpenAsync().ConfigureAwait(false); Assert.Fail("Should throw UnauthorizedException but didn't."); } catch (UnauthorizedException) { // It should always throw UnauthorizedException } } // Check TCP connection to verify there is no connection leak // netstat -na | find "[Your Hub IP]" | find "ESTABLISHED" await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); }
private async Task UploadFile(Client.ITransportSettings[] transportSettings, string filename, bool x509auth = false) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync( DevicePrefix, x509auth?TestDeviceType.X509 : TestDeviceType.Sasl).ConfigureAwait(false); DeviceClient deviceClient; if (x509auth) { X509Certificate2 cert = Configuration.IoTHub.GetCertificateWithPrivateKey(); var auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert); deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, auth, transportSettings); } else { deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transportSettings); } await FileNotificationTestListener.InitAsync().ConfigureAwait(false); using (deviceClient) { using (FileStream fileStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read)) { await deviceClient.UploadToBlobAsync(filename, fileStreamSource).ConfigureAwait(false); } await FileNotificationTestListener.VerifyFileNotification(filename, testDevice.Id).ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); } }
public async Task X509_Cert_Chain_Install_Test_MQTT_TCP() { // arrange var chainCerts = new X509Certificate2Collection { TestConfiguration.CommonCertificates.GetRootCaCertificate(), TestConfiguration.CommonCertificates.GetIntermediate1Certificate(), TestConfiguration.CommonCertificates.GetIntermediate2Certificate() }; using var auth = new DeviceAuthenticationWithX509Certificate( TestConfiguration.IoTHub.X509ChainDeviceName, s_chainCertificateWithPrivateKey, chainCerts); using var deviceClient = DeviceClient.Create( _hostName, auth, DeviceTransportType.Mqtt_Tcp_Only); // act await deviceClient.OpenAsync().ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); // assert ValidateCertsAreInstalled(chainCerts); }
static void Main(string[] args) { try { var cert = new X509Certificate2(@"testDevice01.pfx", "1234"); var auth = new DeviceAuthenticationWithX509Certificate("TestDevice01", cert); var deviceClient = DeviceClient.Create("damienbod.azure-devices.net", auth, TransportType.Amqp_Tcp_Only); if (deviceClient == null) { Console.WriteLine("Failed to create DeviceClient!"); } else { Console.WriteLine("Successfully created DeviceClient!"); SendEvent(deviceClient).Wait(); } Console.WriteLine("Exiting...\n"); } catch (Exception ex) { Console.WriteLine("Error in sample: {0}", ex.Message); } }
private Client.IAuthenticationMethod CreateAuthenticationMethodFromSecurityProvider( SecurityProvider provisioningSecurity, string deviceId) { _verboseLog.WriteLine($"{nameof(CreateAuthenticationMethodFromSecurityProvider)}({deviceId})"); Client.IAuthenticationMethod auth; if (provisioningSecurity is SecurityProviderTpm tpmSecurity) { auth = new DeviceAuthenticationWithTpm(deviceId, tpmSecurity); } else if (provisioningSecurity is SecurityProviderX509 x509Security) { X509Certificate2 cert = x509Security.GetAuthenticationCertificate(); auth = new DeviceAuthenticationWithX509Certificate(deviceId, cert); } else if (provisioningSecurity is SecurityProviderSymmetricKey symmetricKeySecurity) { auth = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, symmetricKeySecurity.GetPrimaryKey()); } else { throw new NotSupportedException($"Unknown provisioningSecurity type."); } return auth; }
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); } } }
// This function create a device with x509 cert and send a message to the iothub on the transport specified. // It then verifies the message is received at the eventHubClient. private async Task SendSingleMessageX509(Client.TransportType transport) { Tuple <string, string> deviceInfo = TestUtil.CreateDeviceWithX509(DevicePrefix, hostName, registryManager); EventHubClient eventHubClient; EventHubReceiver eventHubReceiver = CreateEventHubReceiver(deviceInfo.Item1, out eventHubClient); string certBase64 = Environment.GetEnvironmentVariable("IOTHUB_X509_PFX_CERTIFICATE"); Byte[] buff = Convert.FromBase64String(certBase64); var cert = new X509Certificate2(buff); var auth = new DeviceAuthenticationWithX509Certificate(deviceInfo.Item1, cert); var deviceClient = DeviceClient.Create(deviceInfo.Item2, auth, transport); await deviceClient.OpenAsync(); string payload; string p1Value; Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value); await deviceClient.SendEventAsync(testMessage); var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5)); VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value); await deviceClient.CloseAsync(); await eventHubClient.CloseAsync(); TestUtil.RemoveDevice(deviceInfo.Item1, registryManager); }
public static DeviceClient CreateSelfSignedDevice(TransportType transport, string deviceId) { Console.Write("Connecting to hub.... "); var registryManager = RegistryManager.CreateFromConnectionString(hubConnStr); Console.WriteLine("done"); Console.Write("Creating device with self signed key.... "); var certificate = GetSelfSigned(); var device = new Microsoft.Azure.Devices.Device(deviceId) { Authentication = new AuthenticationMechanism { X509Thumbprint = new X509Thumbprint { PrimaryThumbprint = certificate.Thumbprint } } }; var createdDevice = registryManager.AddDeviceAsync(device).Result; Console.WriteLine($"done. Id='{deviceId}', X509Thumbprint = '{createdDevice.Authentication.X509Thumbprint.PrimaryThumbprint}'"); Console.Write("Connecting to device... "); var auth = new DeviceAuthenticationWithX509Certificate(deviceId, certificate); var client = DeviceClient.Create(hubUrl, auth, transport); Console.WriteLine("done"); return(client); }
private async Task UploadFileAsync(Client.TransportType transport, string filename, bool useX509auth = false) { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync( Logger, _devicePrefix, useX509auth?TestDeviceType.X509 : TestDeviceType.Sasl).ConfigureAwait(false); DeviceClient deviceClient; X509Certificate2 cert = null; DeviceAuthenticationWithX509Certificate x509Auth = null; if (useX509auth) { cert = s_selfSignedCertificate; x509Auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert); deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, x509Auth, transport); } else { deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); } using (deviceClient) { using var fileStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read); // UploadToBlobAsync is obsolete, added [Obsolete] attribute to suppress CS0618 message await deviceClient.UploadToBlobAsync(filename, fileStreamSource).ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); } x509Auth?.Dispose(); }
static void Main(string[] args) { try { //HCL //var cert = new X509Certificate2(@"C:\Certificate\certificatedevice1.pfx", "1234"); //var auth = new DeviceAuthenticationWithX509Certificate("CERT1", cert); //var deviceClient = DeviceClient.Create("asp-iothub.azure-devices.net", auth, TransportType.Mqtt_Tcp_Only); //JnJ Hub var cert = new X509Certificate2(@"C:\MyProjects\Certificate\JnJVerificationCode\Device3\Device3.pfx"); var auth = new DeviceAuthenticationWithX509Certificate("Device3", cert); var deviceClient = DeviceClient.Create("ASP-BI-Lab-IIOT-IotHub.azure-devices.net", auth, TransportType.Mqtt_Tcp_Only); if (deviceClient == null) { Console.WriteLine("Failed to create DeviceClient!"); } else { Console.WriteLine("Successfully created DeviceClient!"); SendEvent(deviceClient).Wait(); } Console.WriteLine("Exiting...\n"); } catch (Exception ex) { Console.WriteLine("Error in sample: {0}", ex.Message); } Console.ReadLine(); }
// Based on https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-security-x509-get-started#create-an-x509-device-for-your-iot-hub static void Main(string[] args) { try { var cert = new X509Certificate2(pfxPath); Console.WriteLine("Certificate Info:"); Console.WriteLine($"Subject: {cert.Subject}"); Console.WriteLine($"Expires: {cert.NotAfter}"); var auth = new DeviceAuthenticationWithX509Certificate(deviceId, cert); var deviceClient = DeviceClient.Create(iotHubFqdn, auth, TransportType.Mqtt_Tcp_Only); if (deviceClient == null) { Console.WriteLine("Failed to create DeviceClient!"); } else { Console.WriteLine("Successfully created DeviceClient using x.509 certificate."); SendEvent(deviceClient).Wait(); } Console.WriteLine("Exiting...\n"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } Console.ReadLine(); }
public void NullX509CertificateAmqpTransportSettingsTest() { string hostName = "acme.azure-devices.net"; var authMethod = new DeviceAuthenticationWithX509Certificate("device1", null); var deviceClient = DeviceClient.Create(hostName, authMethod, new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 100) }); }
static void Main(string[] args) { Console.WriteLine("### Simulated Device with x.509 certificate authorization."); try { var cert = new X509Certificate2(absolutePathToDevicePfxFile, "123"); var auth = new DeviceAuthenticationWithX509Certificate(deviceId, cert); // var deviceClient = DeviceClient.Create(iotHubConnection, auth, TransportType.Amqp_Tcp_Only); var deviceClient = DeviceClient.Create(iotHubConnection, auth, TransportType.Mqtt); if (deviceClient == null) { Console.WriteLine("Failed to create DeviceClient!"); } else { Console.WriteLine("Successfully created DeviceClient!"); SendEvent(deviceClient).Wait(); } Console.WriteLine("Exiting...\n"); } catch (Exception ex) { ShowException(ex); } }
private DeviceClient CreateDeviceClientWithInvalidId(Client.TransportType transportType) { string deviceName = $"DEVICE_NOT_EXIST_{Guid.NewGuid()}"; var auth = new DeviceAuthenticationWithX509Certificate(deviceName, Configuration.IoTHub.GetCertificateWithPrivateKey()); return(DeviceClient.Create(_hostName, 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 async Task UploadFileAsync(Client.TransportType transport, string filename, bool x509auth = false) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync( Logger, _devicePrefix, x509auth?TestDeviceType.X509 : TestDeviceType.Sasl).ConfigureAwait(false); DeviceClient deviceClient; if (x509auth) { X509Certificate2 cert = Configuration.IoTHub.GetCertificateWithPrivateKey(); var auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, cert); deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, auth, transport); } else { deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); } using (deviceClient) { using (var fileStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read)) { await deviceClient.UploadToBlobAsync(filename, fileStreamSource).ConfigureAwait(false); } await deviceClient.CloseAsync().ConfigureAwait(false); } }
public async Task DeviceTwin_Contains_ModelId_X509() { // Setup // Create a device. TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix, TestDeviceType.X509).ConfigureAwait(false); // Send model ID with MQTT connect packet to make the device plug and play. var options = new ClientOptions { ModelId = TestModelId, }; string hostName = HostNameHelper.GetHostName(Configuration.IoTHub.ConnectionString); var auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, Configuration.IoTHub.GetCertificateWithPrivateKey()); using var deviceClient = DeviceClient.Create(hostName, auth, Client.TransportType.Mqtt_Tcp_Only, options); await deviceClient.OpenAsync().ConfigureAwait(false); // Act // Get device twin. using var registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString); Twin twin = await registryManager.GetTwinAsync(testDevice.Device.Id).ConfigureAwait(false); // Assert twin.ModelId.Should().Be(TestModelId, "because the device was created as plug and play"); // Cleanup await registryManager.RemoveDeviceAsync(testDevice.Id).ConfigureAwait(false); }
protected async Task ConnectToEdgeAndSendDataAsync() { var builder = IotHubConnectionStringBuilder.Create(this.iothubConnectionString); DeviceClient deviceClient; if (this.authType == AuthenticationType.Sas) { string leafDeviceConnectionString = $"HostName={builder.HostName};DeviceId={this.deviceId};SharedAccessKey={this.context.Device.Authentication.SymmetricKey.PrimaryKey};GatewayHostName={this.edgeHostName}"; deviceClient = DeviceClient.CreateFromConnectionString(leafDeviceConnectionString, this.deviceTransportSettings); } else { var auth = new DeviceAuthenticationWithX509Certificate(this.deviceId, this.clientCertificate.Expect(() => new InvalidOperationException("Missing client certificate"))); deviceClient = DeviceClient.Create(builder.HostName, this.edgeHostName, auth, this.deviceTransportSettings); } this.context.DeviceClientInstance = Option.Some(deviceClient); Console.WriteLine("Leaf Device client created."); var message = new Message(Encoding.ASCII.GetBytes($"Message from Leaf Device. Msg GUID: {this.context.MessageGuid}")); Console.WriteLine($"Trying to send the message to '{this.edgeHostName}'"); await deviceClient.SendEventAsync(message); Console.WriteLine("Message Sent."); await deviceClient.SetMethodHandlerAsync("DirectMethod", DirectMethod, null); Console.WriteLine("Direct method callback is set."); }
[Ignore] // TODO #582 public void DeviceClient_ValidCertMqtt() { // arrange const string hostName = "acme.azure-devices.net"; X509Certificate2 cert = CertificateHelper.InstallCertificateFromFile(LocalCertFilename, LocalCertPasswordFile); var authMethod = new DeviceAuthenticationWithX509Certificate("device1", cert); // act var deviceClient = DeviceClient.Create( hostName, authMethod, new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_Tcp_Only) { ClientCertificate = cert, RemoteCertificateValidationCallback = (a, b, c, d) => true, }, new MqttTransportSettings(TransportType.Mqtt_WebSocket_Only) { ClientCertificate = cert, RemoteCertificateValidationCallback = (a, b, c, d) => true, } }); // assert? }
public void DeviceClientConnectionStringX509CertificateNullCertificateTest() { string hostName = "acme.azure-devices.net"; var authMethod = new DeviceAuthenticationWithX509Certificate("device1", null); var deviceClient = DeviceClient.Create(hostName, authMethod, TransportType.Amqp_WebSocket_Only); }
[Ignore] // TODO #583 public void DeviceClientConnectionStringX509CertificateDefaultTest() { string hostName = "acme.azure-devices.net"; var cert = CertificateHelper.InstallCertificateFromFile(LocalCertFilename, LocalCertPasswordFile); var authMethod = new DeviceAuthenticationWithX509Certificate("device1", cert); var deviceClient = DeviceClient.Create(hostName, authMethod); }
[Ignore] // TODO #583 public void DeviceClientConnectionStringX509CertificateAmqpWsTest() { string hostName = "acme.azure-devices.net"; var cert = CertificateHelper.InstallCertificateFromFile(LocalCertFilename, LocalCertPasswordFile); var authMethod = new DeviceAuthenticationWithX509Certificate("device1", cert); var deviceClient = DeviceClient.Create(hostName, authMethod, TransportType.Amqp_WebSocket_Only); }