public DummyAuthentication(IAuthenticationMethod authConfig) { if(authConfig.IsDefined("user") == false) throw new ArgumentException("Dummy authentication does not define 'user'-value"); _user = authConfig.GetValue("user"); }
public static IotHubConnectionStringBuilder Create(string hostname, IAuthenticationMethod authenticationMethod) { var iotHubConnectionStringBuilder = new IotHubConnectionStringBuilder { HostName = hostname, AuthenticationMethod = authenticationMethod }; iotHubConnectionStringBuilder.Validate(); return iotHubConnectionStringBuilder; }
/// <summary> /// Create a DeviceClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authMethod">The authentication method that is used</param> /// <returns>DeviceClient</returns> public static HttpDeviceClient Create(string hostname, IAuthenticationMethod authMethod) { if (hostname == null) { throw new ArgumentNullException("hostname"); } if (authMethod == null) { throw new ArgumentNullException("authMethod"); } var connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, authMethod); return CreateFromConnectionString(connectionStringBuilder.ToString()); }
public AuthenticationMechanismChecker(IAuthenticationMethod authConfig) { _authConfig = authConfig; _authType = GenericClassIdentifierFactory.FindTypeForIdentifier<AuthenticationMechanism>(authConfig.AuthIdentifier); if (_authType == null) throw new ArgumentException(string.Format("No AuthenticationMechanism with identifier '{0}' was found", authConfig.AuthIdentifier)); object[] attributes = _authType.GetCustomAttributes(typeof(AuthenticationSettingsAttribute), false); if (attributes == null || attributes.Length == 0) throw new ArgumentException(string.Format("Authentication '{0}' does not provide authentication settings!", authConfig.AuthIdentifier)); _authSettings = (AuthenticationSettingsAttribute)attributes[0]; }
/// <summary> /// Create a DeviceClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <returns>DeviceClient</returns> public static AmqpTransportHandler Create(string hostname, IAuthenticationMethod authenticationMethod) { if (hostname == null) { throw new ArgumentNullException(nameof(hostname)); } if (authenticationMethod == null) { throw new ArgumentNullException(nameof(authenticationMethod)); } IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, authenticationMethod); return CreateFromConnectionString(connectionStringBuilder.ToString()); }
public SslAuthentication(IAuthenticationMethod authConfig) { }
// Async method to send simulated telemetry private static async Task SendDeviceToCloudMessagesAsync(DeviceRegistrationResult device, IAuthenticationMethod auth) { Console.WriteLine($"Testing the provisioned device with IoT Hub..."); using DeviceClient iotClient = DeviceClient.Create(device.AssignedHub, auth); // Initial telemetry values double minTemperature = 20; double minHumidity = 60; var rand = new Random(); while (true) { double currentTemperature = minTemperature + rand.NextDouble() * 15; double currentHumidity = minHumidity + rand.NextDouble() * 20; // Create JSON message string messageBody = JsonSerializer.Serialize( new { temperature = currentTemperature, humidity = currentHumidity, }); using var message = new Message(Encoding.ASCII.GetBytes(messageBody)) { ContentType = "application/json", ContentEncoding = "utf-8", }; // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); // Send the telemetry message await iotClient.SendEventAsync(message); Console.WriteLine($"{DateTime.Now} > Sending message: {messageBody}"); await Task.Delay(5000); } }
public NamedPipeAuthentication(IAuthenticationMethod authConfig) { }
/// <summary> /// Create a DeviceClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportType">The transportType used (Http1 or Amqp)</param> /// <returns>DeviceClient</returns> public static DeviceClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod, TransportType transportType) { return(Create(() => ClientFactory.Create(hostname, gatewayHostname, authenticationMethod, transportType))); }
public async Task UpdateDeviceConnectionTest() { int receivedConnectedStatusCount = 0; ConnectionStatusChangesHandler connectionStatusChangesHandler = null; string hostname = "dummy.azure-devices.net"; string deviceId = "device1"; IClientCredentials GetClientCredentials(TimeSpan tokenExpiryDuration) { string token = TokenHelper.CreateSasToken(hostname, DateTime.UtcNow.AddSeconds(tokenExpiryDuration.TotalSeconds)); var identity = new DeviceIdentity(hostname, deviceId); return(new TokenCredentials(identity, token, string.Empty)); } IDeviceProxy GetMockDeviceProxy() { var deviceProxyMock1 = new Mock <IDeviceProxy>(); deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(true); deviceProxyMock1.Setup(dp => dp.CloseAsync(It.IsAny <Exception>())) .Callback(() => deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(false)) .Returns(Task.CompletedTask); return(deviceProxyMock1.Object); } IClient GetMockedDeviceClient() { var deviceClient = new Mock <IClient>(); deviceClient.SetupGet(dc => dc.IsActive).Returns(true); deviceClient.Setup(dc => dc.CloseAsync()) .Callback(() => deviceClient.SetupGet(dc => dc.IsActive).Returns(false)) .Returns(Task.FromResult(true)); deviceClient.Setup(dc => dc.SetConnectionStatusChangedHandler(It.IsAny <ConnectionStatusChangesHandler>())) .Callback <ConnectionStatusChangesHandler>(c => connectionStatusChangesHandler = c); deviceClient.Setup(dc => dc.OpenAsync()) .Callback(() => { int currentCount = receivedConnectedStatusCount; Assert.NotNull(connectionStatusChangesHandler); connectionStatusChangesHandler.Invoke(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); Assert.Equal(receivedConnectedStatusCount, currentCount); }) .Returns(Task.CompletedTask); return(deviceClient.Object); } IAuthenticationMethod authenticationMethod = null; var deviceClientProvider = new Mock <IClientProvider>(); deviceClientProvider.Setup(dc => dc.Create(It.IsAny <IIdentity>(), It.IsAny <IAuthenticationMethod>(), It.IsAny <ITransportSettings[]>())) .Callback <IIdentity, IAuthenticationMethod, ITransportSettings[]>((s, a, t) => authenticationMethod = a) .Returns(() => GetMockedDeviceClient()); var messageConverterProvider = Mock.Of <IMessageConverterProvider>(); ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>(), TokenProvider, DeviceScopeIdentitiesCache, TimeSpan.FromMinutes(60), true); cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>()); var credentialsCache = Mock.Of <ICredentialsCache>(); IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache, deviceId, "$edgeHub"); IClientCredentials clientCredentials1 = GetClientCredentials(TimeSpan.FromSeconds(10)); Try <ICloudProxy> cloudProxyTry1 = await connectionManager.CreateCloudConnectionAsync(clientCredentials1); Assert.True(cloudProxyTry1.Success); IDeviceProxy deviceProxy1 = GetMockDeviceProxy(); await connectionManager.AddDeviceConnection(clientCredentials1.Identity, deviceProxy1); await Task.Delay(TimeSpan.FromSeconds(10)); Assert.NotNull(authenticationMethod); var deviceTokenRefresher = authenticationMethod as DeviceAuthenticationWithTokenRefresh; Assert.NotNull(deviceTokenRefresher); Task <string> tokenGetter = deviceTokenRefresher.GetTokenAsync(hostname); Assert.False(tokenGetter.IsCompleted); IClientCredentials clientCredentials2 = GetClientCredentials(TimeSpan.FromMinutes(2)); Try <ICloudProxy> cloudProxyTry2 = await connectionManager.CreateCloudConnectionAsync(clientCredentials2); Assert.True(cloudProxyTry2.Success); IDeviceProxy deviceProxy2 = GetMockDeviceProxy(); await connectionManager.AddDeviceConnection(clientCredentials2.Identity, deviceProxy2); await Task.Delay(TimeSpan.FromSeconds(3)); Assert.False(tokenGetter.IsCompleted); IClientCredentials clientCredentials3 = GetClientCredentials(TimeSpan.FromMinutes(10)); Try <ICloudProxy> cloudProxyTry3 = await connectionManager.CreateCloudConnectionAsync(clientCredentials3); Assert.True(cloudProxyTry3.Success); IDeviceProxy deviceProxy3 = GetMockDeviceProxy(); await connectionManager.AddDeviceConnection(clientCredentials3.Identity, deviceProxy3); await Task.Delay(TimeSpan.FromSeconds(23)); Assert.True(tokenGetter.IsCompleted); Assert.Equal(tokenGetter.Result, (clientCredentials3 as ITokenCredentials)?.Token); }
private InternalClient CreateInternalClientFromAuthenticationMethod(string hostname, string gateway, IAuthenticationMethod authMethod, ClientOptions options) { return(ClientFactory.Create(hostname, gateway, authMethod, _transportSettings, options)); }
/// <summary> /// Records a <see cref="AuthenticationResult.Failure"/> authentication attempt for the specified /// <see cref="IAuthenticationMethod"/> . /// </summary> /// <param name="authenticationMethod">An <see cref="IAuthenticationMethod"/> for which to record the result of an authentication attempt.</param> public void RecordFailure(IAuthenticationMethod authenticationMethod) { _failedAuthenticationMethods.Add(authenticationMethod); }
/// <summary> /// Creates a connection string based on the hostname of the IoT Hub and the authentication method passed as a parameter. /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <returns>A new instance of the <see cref="IotHubConnectionStringBuilder"/> class with a populated connection string.</returns> public static IotHubConnectionStringBuilder Create(string hostname, IAuthenticationMethod authenticationMethod) { return(Create(hostname, null, authenticationMethod)); }
public void DeviceClient_IotHubConnectionStringBuilder_Test() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); Assert.IsNotNull(iotHubConnectionStringBuilder.HostName); Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId); Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKey); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKeyName); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessSignature); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey); connectionString = "HostName=acme.azure-devices.net;CredentialType=SharedAccessSignature;DeviceId=device1;SharedAccessSignature=SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"; iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); Assert.IsNotNull(iotHubConnectionStringBuilder.HostName); Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId); Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKey); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessSignature); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); Assert.IsNotNull(iotHubConnectionStringBuilder.HostName); Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId); Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKey); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKeyName); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessSignature); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey); connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;DeviceId=device1;SharedAccessSignature=SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"; iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); Assert.IsNotNull(iotHubConnectionStringBuilder.HostName); Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId); Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKey); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKeyName); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessSignature); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); try { iotHubConnectionStringBuilder.HostName = "adshgfvyregferuehfiuehr"; Assert.Fail("Expected FormatException"); } catch (FormatException) { } iotHubConnectionStringBuilder.HostName = "acme.azure-devices.net"; iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey("Device1", "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device1"); iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithToken("Device2", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device2"); iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithSharedAccessPolicyKey("Device3", "AllAccess", "KQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "KQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device3"); iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithToken("Device4", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device4"); IAuthenticationMethod authMethod = AuthenticationMethodFactory.CreateAuthenticationWithToken("Device5", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme1.azure-devices.net", authMethod); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme1.azure-devices.net"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device5"); authMethod = new DeviceAuthenticationWithSharedAccessPolicyKey("Device3", "AllAccess", "KQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme2.azure-devices.net", authMethod); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey); Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme2.azure-devices.net"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "KQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device3"); authMethod = new DeviceAuthenticationWithToken("Device2", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme3.azure-devices.net", authMethod); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme3.azure-devices.net"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=poifbMLdBGtCJknubF2FW6FLn5vND5k1IKoeQ%2bONgkE%3d&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device2"); authMethod = new DeviceAuthenticationWithRegistrySymmetricKey("Device1", "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme4.azure-devices.net", authMethod); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey); Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme4.azure-devices.net"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device1"); }
/// <summary> /// Create a ModuleClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportSettings">Prioritized list of transportTypes and their settings</param> /// <param name="options">The options that allow configuration of the module client instance during initialization.</param> /// <returns>ModuleClient</returns> public static ModuleClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod, ITransportSettings[] transportSettings, ClientOptions options = default) { return(Create(() => ClientFactory.Create(hostname, gatewayHostname, authenticationMethod, transportSettings, options))); }
/// <summary> /// Create a InternalClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportType">The transportType used (Http1, Amqp or Mqtt), <see cref="TransportType"/></param> /// <param name="options">The options that allow configuration of the device client instance during initialization.</param> /// <returns>InternalClient</returns> internal static InternalClient Create( string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod, TransportType transportType, ClientOptions options = default) { if (hostname == null) { throw new ArgumentNullException(nameof(hostname)); } if (authenticationMethod == null) { throw new ArgumentNullException(nameof(authenticationMethod)); } if (transportType != TransportType.Amqp_Tcp_Only && transportType != TransportType.Mqtt_Tcp_Only && authenticationMethod is DeviceAuthenticationWithX509Certificate certificate && certificate.ChainCertificates != null) { throw new ArgumentException("Certificate chains are only supported on Amqp_Tcp_Only and Mqtt_Tcp_Only"); } if (!string.IsNullOrWhiteSpace(options?.ModelId) && transportType == TransportType.Http1) { throw new InvalidOperationException("Plug and Play is not supported over the HTTP transport."); } var connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, gatewayHostname, authenticationMethod); // Make sure client options is initialized with the correct transport setting. EnsureOptionsIsSetup(connectionStringBuilder.Certificate, ref options); if (authenticationMethod is DeviceAuthenticationWithX509Certificate) { if (connectionStringBuilder.Certificate == null) { throw new ArgumentException("No certificate was found. To use certificate authentication certificate must be present."); } #pragma warning disable CA2000 // This is returned to client so cannot be disposed here. InternalClient dc = CreateFromConnectionString( connectionStringBuilder.ToString(), PopulateCertificateInTransportSettings(connectionStringBuilder, transportType), options); #pragma warning restore CA2000 dc.Certificate = connectionStringBuilder.Certificate; // Install all the intermediate certificates in the chain if specified. if (connectionStringBuilder.ChainCertificates != null) { try { CertificateInstaller.EnsureChainIsInstalled(connectionStringBuilder.ChainCertificates); } catch (Exception ex) { if (Logging.IsEnabled) { Logging.Error(null, $"{nameof(CertificateInstaller)} failed to read or write to cert store due to: {ex}"); } throw new UnauthorizedException($"Failed to provide certificates in the chain - {ex.Message}", ex); } } return(dc); } return(CreateFromConnectionString(connectionStringBuilder.ToString(), authenticationMethod, transportType, null, options)); }
internal static InternalClient CreateFromConnectionString( string connectionString, IAuthenticationMethod authenticationMethod, ITransportSettings[] transportSettings, IDeviceClientPipelineBuilder pipelineBuilder, ClientOptions options = default) { if (connectionString == null) { throw new ArgumentNullException(nameof(connectionString)); } if (transportSettings == null) { throw new ArgumentNullException(nameof(transportSettings)); } if (transportSettings.Length == 0) { throw new ArgumentOutOfRangeException(nameof(connectionString), "Must specify at least one TransportSettings instance"); } if (!string.IsNullOrWhiteSpace(options?.ModelId) && transportSettings.Any(x => x.GetTransportType() == TransportType.Http1)) { throw new InvalidOperationException("Plug and Play is not supported over the HTTP transport."); } var builder = IotHubConnectionStringBuilder.CreateWithIAuthenticationOverride( connectionString, authenticationMethod); // Clients that derive their authentication method from AuthenticationWithTokenRefresh will need to specify // the token time to live and renewal buffer values through the corresponding AuthenticationWithTokenRefresh // implementation constructors instead. if (!(builder.AuthenticationMethod is AuthenticationWithTokenRefresh)) { builder.SasTokenTimeToLive = options?.SasTokenTimeToLive ?? default; builder.SasTokenRenewalBuffer = options?.SasTokenRenewalBuffer ?? default; } IotHubConnectionString iotHubConnectionString = builder.ToIotHubConnectionString(); foreach (ITransportSettings transportSetting in transportSettings) { switch (transportSetting.GetTransportType()) { case TransportType.Amqp_WebSocket_Only: case TransportType.Amqp_Tcp_Only: if (!(transportSetting is AmqpTransportSettings)) { throw new InvalidOperationException("Unknown implementation of ITransportSettings type"); } break; case TransportType.Http1: if (!(transportSetting is Http1TransportSettings)) { throw new InvalidOperationException("Unknown implementation of ITransportSettings type"); } break; case TransportType.Mqtt_WebSocket_Only: case TransportType.Mqtt_Tcp_Only: if (!(transportSetting is MqttTransportSettings)) { throw new InvalidOperationException("Unknown implementation of ITransportSettings type"); } break; default: throw new InvalidOperationException("Unsupported Transport Type {0}".FormatInvariant(transportSetting.GetTransportType())); } } if (authenticationMethod is DeviceAuthenticationWithX509Certificate && builder.Certificate == null) { throw new ArgumentException("No certificate was found. To use certificate authentication certificate must be present."); } // Make sure client options is initialized with the correct transport setting. EnsureOptionsIsSetup(builder.Certificate, ref options); pipelineBuilder ??= BuildPipeline(); // Defer concrete InternalClient creation to OpenAsync var client = new InternalClient(iotHubConnectionString, transportSettings, pipelineBuilder, options); if (Logging.IsEnabled) { Logging.CreateFromConnectionString( client, $"HostName={iotHubConnectionString.HostName};DeviceId={iotHubConnectionString.DeviceId};ModuleId={iotHubConnectionString.ModuleId}", transportSettings, options); } return(client); }
/// <summary> /// Create an Amqp InternalClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="options">The options that allow configuration of the device client instance during initialization.</param> /// <returns>InternalClient</returns> internal static InternalClient Create(string hostname, IAuthenticationMethod authenticationMethod, ClientOptions options = default) { return(Create(hostname, authenticationMethod, TransportType.Amqp, options)); }
public UnixSocketAuthentication(IAuthenticationMethod authConfig) { }
/// <summary> /// Creates a connection string based on the hostname of the IoT Hub, the hostname of Gateway and the authentication method passed as a parameter. /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="gatewayHostname">The fully-qualified DNS hostname of the gateway</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <returns>A new instance of the <see cref="IotHubConnectionStringBuilder"/> class with a populated connection string.</returns> public static IotHubConnectionStringBuilder Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod) { var iotHubConnectionStringBuilder = new IotHubConnectionStringBuilder() { HostName = hostname, GatewayHostName = gatewayHostname, AuthenticationMethod = authenticationMethod }; iotHubConnectionStringBuilder.Validate(); return(iotHubConnectionStringBuilder); }
/// <summary> /// Creates a disposable DeviceClient from the specified parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportType">The transportType used (Http1, Amqp or Mqtt), <see cref="TransportType"/></param> /// <param name="options">The options that allow configuration of the device client instance during initialization.</param> /// <returns>A disposable DeviceClient instance</returns> public static DeviceClient Create(string hostname, IAuthenticationMethod authenticationMethod, TransportType transportType, ClientOptions options = default) { return(Create(() => ClientFactory.Create(hostname, authenticationMethod, transportType, options))); }
public JellyfinClient(Uri serverAddress, IAuthenticationMethod authentication) : base(serverAddress, authentication, null) { }
public async Task RefreshTokenWithRetryTest() { string iothubHostName = "test.azure-devices.net"; string deviceId = "device1"; IClientCredentials GetClientCredentialsWithExpiringToken() { string token = TokenHelper.CreateSasToken(iothubHostName, DateTime.UtcNow.AddMinutes(3)); var identity = new DeviceIdentity(iothubHostName, deviceId); return(new TokenCredentials(identity, token, string.Empty)); } IClientCredentials GetClientCredentialsWithNonExpiringToken() { string token = TokenHelper.CreateSasToken(iothubHostName, DateTime.UtcNow.AddMinutes(10)); var identity = new DeviceIdentity(iothubHostName, deviceId); return(new TokenCredentials(identity, token, string.Empty)); } IAuthenticationMethod authenticationMethod = null; IClientProvider clientProvider = GetMockDeviceClientProviderWithToken((s, a, t) => authenticationMethod = a); var transportSettings = new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only) }; var receivedStatuses = new List <CloudConnectionStatus>(); void ConnectionStatusHandler(string id, CloudConnectionStatus status) => receivedStatuses.Add(status); var messageConverterProvider = new MessageConverterProvider(new Dictionary <Type, IMessageConverter> { [typeof(TwinCollection)] = Mock.Of <IMessageConverter>() }); var cloudConnection = new CloudConnection(ConnectionStatusHandler, transportSettings, messageConverterProvider, clientProvider, Mock.Of <ICloudListener>(), TokenProvider, DeviceScopeIdentitiesCache, TimeSpan.FromMinutes(60), true); IClientCredentials clientCredentialsWithExpiringToken1 = GetClientCredentialsWithExpiringToken(); ICloudProxy cloudProxy1 = await cloudConnection.CreateOrUpdateAsync(clientCredentialsWithExpiringToken1); Assert.True(cloudProxy1.IsActive); Assert.Equal(cloudProxy1, cloudConnection.CloudProxy.OrDefault()); Assert.NotNull(authenticationMethod); var deviceAuthenticationWithTokenRefresh = authenticationMethod as DeviceAuthenticationWithTokenRefresh; Assert.NotNull(deviceAuthenticationWithTokenRefresh); // Try to refresh token but get an expiring token Task <string> getTokenTask = deviceAuthenticationWithTokenRefresh.GetTokenAsync(iothubHostName); Assert.False(getTokenTask.IsCompleted); Assert.Equal(1, receivedStatuses.Count); Assert.Equal(receivedStatuses[0], CloudConnectionStatus.TokenNearExpiry); ICloudProxy cloudProxy2 = await cloudConnection.CreateOrUpdateAsync(clientCredentialsWithExpiringToken1); // Wait for the task to process await Task.Delay(TimeSpan.FromSeconds(5)); Assert.False(getTokenTask.IsCompletedSuccessfully); Assert.Equal(cloudProxy2, cloudConnection.CloudProxy.OrDefault()); Assert.True(cloudProxy2.IsActive); Assert.True(cloudProxy1.IsActive); Assert.Equal(cloudProxy1, cloudProxy2); // Wait for 20 secs for retry to happen await Task.Delay(TimeSpan.FromSeconds(20)); // Check if retry happened Assert.Equal(2, receivedStatuses.Count); Assert.Equal(receivedStatuses[1], CloudConnectionStatus.TokenNearExpiry); IClientCredentials clientCredentialsWithNonExpiringToken = GetClientCredentialsWithNonExpiringToken(); ICloudProxy cloudProxy3 = await cloudConnection.CreateOrUpdateAsync(clientCredentialsWithNonExpiringToken); // Wait for the task to complete await Task.Delay(TimeSpan.FromSeconds(5)); Assert.True(getTokenTask.IsCompletedSuccessfully); Assert.Equal(cloudProxy3, cloudConnection.CloudProxy.OrDefault()); Assert.True(cloudProxy3.IsActive); Assert.True(cloudProxy1.IsActive); Assert.Equal(cloudProxy1, cloudProxy3); Assert.Equal(getTokenTask.Result, (clientCredentialsWithNonExpiringToken as ITokenCredentials)?.Token); }
public JellyfinClient(Uri serverAddress, IAuthenticationMethod authentication, JellyfinClientOptions options) : base(serverAddress, authentication, options) { }
/// <summary> /// Create an Amqp DeviceClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <returns>DeviceClient</returns> public static DeviceClient Create(string hostname, IAuthenticationMethod authenticationMethod) { return(Create(() => ClientFactory.Create(hostname, authenticationMethod))); }
public IClient Create(IIdentity identity, IAuthenticationMethod authenticationMethod, ITransportSettings[] transportSettings) => new ConnectivityAwareClient(this.underlyingClientProvider.Create(identity, authenticationMethod, transportSettings), this.deviceConnectivityManager, identity);
/// <summary> /// Create a DeviceClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportSettings">Prioritized list of transportTypes and their settings</param> /// <returns>DeviceClient</returns> public static DeviceClient Create(string hostname, IAuthenticationMethod authenticationMethod, ITransportSettings[] transportSettings) { return(Create(() => ClientFactory.Create(hostname, authenticationMethod, transportSettings))); }
/// <summary> /// Create an Amqp ModuleClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param> /// <returns>ModuleClient</returns> public static ModuleClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod) { return(Create(() => ClientFactory.Create(hostname, gatewayHostname, authenticationMethod))); }
void SetAuthenticationMethod(IAuthenticationMethod authMethod) { if (authMethod == null) { throw new ArgumentNullException("authMethod"); } authMethod.Populate(this); this.authenticationMethod = authMethod; this.Validate(); }
/// <summary> /// Create a InternalClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportSettings">Prioritized list of transportTypes and their settings</param> /// <returns>InternalClient</returns> public static InternalClient Create(string hostname, IAuthenticationMethod authenticationMethod, ITransportSettings[] transportSettings) { return(Create(hostname, null, authenticationMethod, transportSettings)); }
/// <summary> /// Create a InternalClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportType">The transportType used (Http1, Amqp or Mqtt), <see cref="TransportType"/></param> /// <param name="options">The options that allow configuration of the device client instance during initialization.</param> /// <returns>InternalClient</returns> public static InternalClient Create(string hostname, IAuthenticationMethod authenticationMethod, TransportType transportType, ClientOptions options = default) { return(Create(hostname, null, authenticationMethod, transportType, options)); }
/// <summary> /// Create an Amqp DeviceClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <returns>DeviceClient</returns> public static DeviceClient Create(string hostname, IAuthenticationMethod authenticationMethod) { #if WINDOWS_UWP || PCL return Create(hostname, authenticationMethod, TransportType.Http1); #else return Create(hostname, authenticationMethod, TransportType.Amqp); #endif }
/// <summary> /// Create an Amqp DeviceClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <returns>DeviceClient</returns> public static DeviceClient Create(string hostname, IAuthenticationMethod authenticationMethod) { return Create(hostname, authenticationMethod, TransportType.Amqp); }
/// <summary> /// Create a DeviceClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportSettings">Prioritized list of transportTypes and their settings</param> /// <returns>DeviceClient</returns> public static DeviceClient Create(string hostname, IAuthenticationMethod authenticationMethod, [System.Runtime.InteropServices.WindowsRuntime.ReadOnlyArrayAttribute] ITransportSettings[] transportSettings) { if (hostname == null) { throw new ArgumentNullException("hostname"); } if (authenticationMethod == null) { throw new ArgumentNullException("authenticationMethod"); } var connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, authenticationMethod); #if !WINDOWS_UWP && !PCL && !NETMF if (authenticationMethod is DeviceAuthenticationWithX509Certificate) { if (connectionStringBuilder.Certificate == null) { throw new ArgumentException("certificate must be present in DeviceAuthenticationWithX509Certificate"); } return CreateFromConnectionString(connectionStringBuilder.ToString(), PopulateCertificateInTransportSettings(connectionStringBuilder, transportSettings)); } #endif return CreateFromConnectionString(connectionStringBuilder.ToString(), transportSettings); }
internal static InternalClient CreateFromConnectionString( string connectionString, IAuthenticationMethod authenticationMethod, ITransportSettings[] transportSettings, IDeviceClientPipelineBuilder pipelineBuilder) { if (connectionString == null) { throw new ArgumentNullException(nameof(connectionString)); } if (transportSettings == null) { throw new ArgumentNullException(nameof(transportSettings)); } if (transportSettings.Length == 0) { throw new ArgumentOutOfRangeException(nameof(connectionString), "Must specify at least one TransportSettings instance"); } var builder = IotHubConnectionStringBuilder.CreateWithIAuthenticationOverride( connectionString, authenticationMethod); IotHubConnectionString iotHubConnectionString = builder.ToIotHubConnectionString(); foreach (ITransportSettings transportSetting in transportSettings) { switch (transportSetting.GetTransportType()) { case TransportType.Amqp_WebSocket_Only: case TransportType.Amqp_Tcp_Only: if (!(transportSetting is AmqpTransportSettings)) { throw new InvalidOperationException("Unknown implementation of ITransportSettings type"); } break; case TransportType.Http1: if (!(transportSetting is Http1TransportSettings)) { throw new InvalidOperationException("Unknown implementation of ITransportSettings type"); } break; case TransportType.Mqtt_WebSocket_Only: case TransportType.Mqtt_Tcp_Only: if (!(transportSetting is MqttTransportSettings)) { throw new InvalidOperationException("Unknown implementation of ITransportSettings type"); } break; default: throw new InvalidOperationException("Unsupported Transport Type {0}".FormatInvariant(transportSetting.GetTransportType())); } } pipelineBuilder = pipelineBuilder ?? BuildPipeline(); // Defer concrete InternalClient creation to OpenAsync var client = new InternalClient(iotHubConnectionString, transportSettings, pipelineBuilder); if (Logging.IsEnabled) { Logging.CreateFromConnectionString(client, $"HostName={iotHubConnectionString.HostName};DeviceId={iotHubConnectionString.DeviceId}", transportSettings); } return(client); }
public void DeviceClientIotHubConnectionStringBuilderTest() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=device1-.+%_#*?!(),=@;$';SharedAccessKey=dGVzdFN0cmluZzE="; var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); Assert.IsNotNull(iotHubConnectionStringBuilder.HostName); Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId); Assert.IsNull(iotHubConnectionStringBuilder.GatewayHostName); Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKey); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKeyName); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessSignature); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey); connectionString = "HostName=acme.azure-devices.net;GatewayHostName=test;SharedAccessKeyName=AllAccessKey;DeviceId=device1;SharedAccessKey=dGVzdFN0cmluZzE="; iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); Assert.IsNotNull(iotHubConnectionStringBuilder.HostName); Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId); Assert.IsNotNull(iotHubConnectionStringBuilder.GatewayHostName); Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKey); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKeyName); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessSignature); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey); connectionString = "HostName=acme.azure-devices.net;CredentialType=SharedAccessSignature;DeviceId=device1;SharedAccessSignature=SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"; iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); Assert.IsNotNull(iotHubConnectionStringBuilder.HostName); Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId); Assert.IsNull(iotHubConnectionStringBuilder.GatewayHostName); Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKey); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessSignature); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;DeviceId=device1;SharedAccessKey=dGVzdFN0cmluZzE="; iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); Assert.IsNotNull(iotHubConnectionStringBuilder.HostName); Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId); Assert.IsNull(iotHubConnectionStringBuilder.GatewayHostName); Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessKey); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKeyName); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessSignature); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey); connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;DeviceId=device1;SharedAccessSignature=SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"; iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); Assert.IsNotNull(iotHubConnectionStringBuilder.HostName); Assert.IsNotNull(iotHubConnectionStringBuilder.DeviceId); Assert.IsNull(iotHubConnectionStringBuilder.GatewayHostName); Assert.IsNotNull(iotHubConnectionStringBuilder.AuthenticationMethod); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKey); Assert.IsNull(iotHubConnectionStringBuilder.SharedAccessKeyName); Assert.IsNotNull(iotHubConnectionStringBuilder.SharedAccessSignature); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); try { iotHubConnectionStringBuilder.HostName = "adshgfvyregferuehfiuehr"; Assert.Fail("Expected FormatException"); } catch (FormatException) { } iotHubConnectionStringBuilder.HostName = "acme.azure-devices.net"; iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey("Device1-.+%_#*?!(),=@;$'", "dGVzdFN0cmluZzE="); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "dGVzdFN0cmluZzE="); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device1-.+%_#*?!(),=@;$'"); iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithToken("Device2", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device2"); iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithSharedAccessPolicyKey("Device3", "AllAccess", "dGVzdFN0cmluZzI="); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "dGVzdFN0cmluZzI="); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device3"); iotHubConnectionStringBuilder.AuthenticationMethod = new DeviceAuthenticationWithToken("Device4", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device4"); IAuthenticationMethod authMethod = AuthenticationMethodFactory.CreateAuthenticationWithToken("Device5", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme1.azure-devices.net", authMethod); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme1.azure-devices.net"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device5"); authMethod = new DeviceAuthenticationWithSharedAccessPolicyKey("Device3", "AllAccess", "dGVzdFN0cmluZzI="); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme2.azure-devices.net", authMethod); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithSharedAccessPolicyKey); Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme2.azure-devices.net"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "dGVzdFN0cmluZzI="); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device3"); authMethod = new DeviceAuthenticationWithToken("Device2", "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme3.azure-devices.net", authMethod); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithToken); Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme3.azure-devices.net"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == "SharedAccessSignature sr=dh%3a%2f%2facme.azure-devices.net&sig=dGVzdFN0cmluZzU=&se=87824124985&skn=AllAccessKey"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == null); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device2"); authMethod = new DeviceAuthenticationWithRegistrySymmetricKey("Device1-.+%_#*?!(),=@;$'", "dGVzdFN0cmluZzE="); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("acme4.azure-devices.net", authMethod); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey); Assert.IsTrue(iotHubConnectionStringBuilder.HostName == "acme4.azure-devices.net"); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessSignature == null); Assert.IsTrue(iotHubConnectionStringBuilder.SharedAccessKey == "dGVzdFN0cmluZzE="); Assert.IsTrue(iotHubConnectionStringBuilder.DeviceId == "Device1-.+%_#*?!(),=@;$'"); string hostName = "acme.azure-devices.net"; string gatewayHostname = "gateway.acme.azure-devices.net"; IAuthenticationMethod authenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey("Device1-.+%_#*?!(),=@;$'", "dGVzdFN0cmluZzE="); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(hostName, gatewayHostname, authenticationMethod); Assert.AreEqual(gatewayHostname, iotHubConnectionStringBuilder.GatewayHostName); Assert.AreEqual(hostName, iotHubConnectionStringBuilder.HostName); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey); hostName = "acme.azure-devices.net"; authenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey("Device1-.+%_#*?!(),=@;$'", "dGVzdFN0cmluZzE="); iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(hostName, authenticationMethod); Assert.AreEqual(hostName, iotHubConnectionStringBuilder.HostName); Assert.IsTrue(iotHubConnectionStringBuilder.AuthenticationMethod is DeviceAuthenticationWithRegistrySymmetricKey); Assert.IsNull(iotHubConnectionStringBuilder.GatewayHostName); }
/// <summary> /// Create a DeviceClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportType">The transportType used (Http1 or Amqp)</param> /// <returns>DeviceClient</returns> public static DeviceClient Create(string hostname, IAuthenticationMethod authenticationMethod, TransportType transportType) { if (hostname == null) { throw new ArgumentNullException(nameof(hostname)); } if (authenticationMethod == null) { throw new ArgumentNullException(nameof(authenticationMethod)); } var connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, authenticationMethod); #if !WINDOWS_UWP && !PCL && !NETMF if (authenticationMethod is DeviceAuthenticationWithX509Certificate) { if (connectionStringBuilder.Certificate == null) { throw new ArgumentException("certificate must be present in DeviceAuthenticationWithX509Certificate"); } return CreateFromConnectionString(connectionStringBuilder.ToString(), PopulateCertificateInTransportSettings(connectionStringBuilder, transportType)); } #endif return CreateFromConnectionString(connectionStringBuilder.ToString(), transportType); }
/// <summary> /// Create an Amqp InternalClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param> /// <returns>InternalClient</returns> public static InternalClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod) { return(Create(hostname, gatewayHostname, authenticationMethod, TransportType.Amqp)); }
/// <summary> /// Create a InternalClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportType">The transportType used (Http1 or Amqp)</param> /// <returns>InternalClient</returns> public static InternalClient Create(string hostname, IAuthenticationMethod authenticationMethod, TransportType transportType) { return(Create(hostname, null, authenticationMethod, transportType)); }
/// <summary> /// Create a disposable, Amqp DeviceClient from the specified parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="options">The options that allow configuration of the device client instance during initialization.</param> /// <returns>A disposable DeviceClient instance</returns> public static DeviceClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod, ClientOptions options = default) { return(Create(() => ClientFactory.Create(hostname, gatewayHostname, authenticationMethod, options))); }
internal static IAuthenticationMethod DeriveAuthenticationMethod(IAuthenticationMethod currentAuthenticationMethod, IotHubDeviceIdentity deviceIdentity) { switch (deviceIdentity.Scope) { case AuthenticationScope.None: var policyKeyAuth = currentAuthenticationMethod as DeviceAuthenticationWithSharedAccessPolicyKey; if (policyKeyAuth != null) { return new DeviceAuthenticationWithSharedAccessPolicyKey(deviceIdentity.Id, policyKeyAuth.PolicyName, policyKeyAuth.Key); } var deviceKeyAuth = currentAuthenticationMethod as DeviceAuthenticationWithRegistrySymmetricKey; if (deviceKeyAuth != null) { return new DeviceAuthenticationWithRegistrySymmetricKey(deviceIdentity.Id, deviceKeyAuth.DeviceId); } var deviceTokenAuth = currentAuthenticationMethod as DeviceAuthenticationWithToken; if (deviceTokenAuth != null) { return new DeviceAuthenticationWithToken(deviceIdentity.Id, deviceTokenAuth.Token); } throw new InvalidOperationException(""); case AuthenticationScope.SasToken: return new DeviceAuthenticationWithToken(deviceIdentity.Id, deviceIdentity.Secret); case AuthenticationScope.DeviceKey: return new DeviceAuthenticationWithRegistrySymmetricKey(deviceIdentity.Id, deviceIdentity.Secret); case AuthenticationScope.HubKey: return new DeviceAuthenticationWithSharedAccessPolicyKey(deviceIdentity.Id, deviceIdentity.PolicyName, deviceIdentity.Secret); default: throw new InvalidOperationException("Unexpected AuthenticationScope value: " + deviceIdentity.Scope); } }
private async Task <DeviceClient> ResolveDeviceClient(string deviceId, string sasToken = null, DateTime?tokenExpiration = null) { try { var deviceClient = await cache.GetOrCreateAsync <DeviceClient>(deviceId, async (cacheEntry) => { IAuthenticationMethod auth = null; if (string.IsNullOrEmpty(sasToken)) { auth = new DeviceAuthenticationWithSharedAccessPolicyKey(deviceId, this.serverOptions.AccessPolicyName, this.serverOptions.AccessPolicyKey); } else { auth = new DeviceAuthenticationWithToken(deviceId, sasToken); } var newDeviceClient = DeviceClient.Create( this.serverOptions.IoTHubHostName, auth, new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only) { AmqpConnectionPoolSettings = new AmqpConnectionPoolSettings() { Pooling = true, MaxPoolSize = (uint)this.serverOptions.MaxPoolSize, } } } ); newDeviceClient.OperationTimeoutInMilliseconds = (uint)this.serverOptions.DeviceOperationTimeout; await newDeviceClient.OpenAsync(); if (this.serverOptions.DirectMethodEnabled) { await newDeviceClient.SetMethodDefaultHandlerAsync(this.serverOptions.DirectMethodCallback, deviceId); } if (!tokenExpiration.HasValue) { tokenExpiration = DateTime.UtcNow.AddMinutes(this.serverOptions.DefaultDeviceCacheInMinutes); } cacheEntry.SetAbsoluteExpiration(tokenExpiration.Value); cacheEntry.RegisterPostEvictionCallback(this.CacheEntryRemoved, deviceId); this.logger.LogInformation($"Connection to device {deviceId} has been established, valid until {tokenExpiration.Value.ToString()}"); registeredDevices.AddDevice(deviceId); return(newDeviceClient); }); return(deviceClient); } catch (Exception ex) { this.logger.LogError(ex, $"Could not connect device {deviceId}"); } return(null); }