// This method receives the the provisioning device client and security // instances created earlier. private static async Task <DeviceClient> ProvisionDevice( ProvisioningDeviceClient provisioningDeviceClient, SecurityProviderSymmetricKey security) { // The provisioningDeviceClient.RegisterAsync() // is called, which returns a DeviceRegistrationResult instance. // This result contains a number of properties including the DeviceId, // AssignedHub and the Status. var result = await provisioningDeviceClient .RegisterAsync() .ConfigureAwait(false); Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}"); // The method then checks to ensure that the provisioning status has // been set and throws an exception if the device is not Assigned. // Other possible results here include Unassigned, Assigning, // Failed and Disabled. if (result.Status != ProvisioningRegistrationStatusType.Assigned) { throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'"); } // The DeviceAuthenticationWithRegistrySymmetricKey class simplifies // the creation of an IoT Hub connection string using the device // ID and the Primary Symmetric Key var auth = new DeviceAuthenticationWithRegistrySymmetricKey( result.DeviceId, security.GetPrimaryKey()); // Finally, a DeviceClient instance is returned that is connected // to the desired IoT Hub, using the authentication created above, // and using the AMQP protocol. return(DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp)); }
public async Task RunSampleAsync() { // When registering with a symmetric key using a group enrollment, the provided key will not // work for a specific device, rather it must be computed based on two values: the group enrollment // key and the desired device Id. if (_parameters.EnrollmentType == EnrollmentType.Group) { _parameters.PrimaryKey = ComputeDerivedSymmetricKey(_parameters.PrimaryKey, _parameters.Id); } Console.WriteLine($"Initializing the device provisioning client..."); // For individual enrollments, the first parameter must be the registration Id, where in the enrollment // the device Id is already chosen. However, for group enrollments the device Id can be requested by // the device, as long as the key has been computed using that value. // Also, the secondary could could be included, but was left out for the simplicity of this sample. using var security = new SecurityProviderSymmetricKey( _parameters.Id, _parameters.PrimaryKey, null); using var transportHandler = GetTransportHandler(); ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( _parameters.GlobalDeviceEndpoint, _parameters.IdScope, security, transportHandler); Console.WriteLine($"Initialized for registration Id {security.GetRegistrationID()}."); Console.WriteLine("Registering with the device provisioning service..."); DeviceRegistrationResult result = await provClient.RegisterAsync(); Console.WriteLine($"Registration status: {result.Status}."); if (result.Status != ProvisioningRegistrationStatusType.Assigned) { Console.WriteLine($"Registration status did not assign a hub, so exiting this sample."); return; } Console.WriteLine($"Device {result.DeviceId} registered to {result.AssignedHub}."); Console.WriteLine("Creating symmetric key authentication for IoT Hub..."); IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey( result.DeviceId, security.GetPrimaryKey()); Console.WriteLine($"Testing the provisioned device with IoT Hub..."); using DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, _parameters.TransportType); Console.WriteLine("Sending a telemetry message..."); using var message = new Message(Encoding.UTF8.GetBytes("TestMessage")); await iotClient.SendEventAsync(message); Console.WriteLine("Finished."); }
public async Task <Microsoft.Azure.Devices.Client.DeviceClient> ProvisionAsync <DeviceClient>(DataStorage storage) { var connStringContent = storage.Read("ConnectionString"); DevicePortalInfoModel model = JsonConvert.DeserializeObject <DevicePortalInfoModel>(connStringContent); string scope = model.Device.ID_Scope; string primaryKey = model.Device.PrimaryKey; string secondaryKey = model.Device.SecondaryKey; string registrationId = model.Device.RegistrationId; _sendTelemetry = false; using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey)) { using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly)) { _sendTelemetry = false; ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, scope, security, transport); DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false); if (result.Status != ProvisioningRegistrationStatusType.Assigned) { return(null); } Console.WriteLine($"Provisioninged device : {result.DeviceId} at {result.AssignedHub}"); var client = Microsoft.Azure.Devices.Client.DeviceClient.Create(result.AssignedHub, model.Auth, TransportType.Amqp); client.SetMethodHandlerAsync("Reprovision", ReprovisionHandler, null).GetAwaiter().GetResult(); client.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdated, null).GetAwaiter().GetResult(); // TODO:Save new connection information var auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, security.GetPrimaryKey()); var host = result.AssignedHub; var builder = IotHubConnectionStringBuilder.Create(host, auth); var device = new DevicePortalInfoModel { Host = result.AssignedHub, Auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, security.GetPrimaryKey()), Device = new DeviceModel { ID_Scope = scope, PrimaryKey = security.GetPrimaryKey(), SecondaryKey = security.GetSecondaryKey(), RegistrationId = result.RegistrationId, DeviceId = result.DeviceId }, ConnectionString = builder.ToString() }; _storage.Write(DataStorage.DeviceConnectionString, JsonConvert.SerializeObject(device)); return(client); } } }
public override DeviceProvisioningServiceRuntimeClient CreateClient(Uri uri, HttpClientHandler httpClientHandler) { var serviceCredentials = new SymmetricKeyCredentials(_security.GetPrimaryKey()); var dpsClient = new DeviceProvisioningServiceRuntimeClient( uri, serviceCredentials, httpClientHandler, new ApiVersionDelegatingHandler()); dpsClient.HttpClient.Timeout = TimeoutConstant; return(dpsClient); }
// INSERT ProvisionDevice method below here private static async Task <DeviceClient> ProvisionDevice(ProvisioningDeviceClient provisioningDeviceClient, SecurityProviderSymmetricKey security) { var result = await provisioningDeviceClient.RegisterAsync().ConfigureAwait(false); Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}"); if (result.Status != ProvisioningRegistrationStatusType.Assigned) { throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'"); } var auth = new DeviceAuthenticationWithRegistrySymmetricKey( result.DeviceId, security.GetPrimaryKey()); return(DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp)); }
public override AmqpSettings CreateAmqpSettings(string idScope) { var settings = new AmqpSettings(); var saslProvider = new SaslTransportProvider(); saslProvider.Versions.Add(AmqpConstants.DefaultProtocolVersion); settings.TransportProviders.Add(saslProvider); SaslPlainHandler saslHandler = new SaslPlainHandler(); saslHandler.AuthenticationIdentity = $"{idScope}/registrations/{_security.GetRegistrationID()}"; string key = _security.GetPrimaryKey(); saslHandler.Password = ProvisioningSasBuilder.BuildSasSignature("registration", key, saslHandler.AuthenticationIdentity, TimeSpan.FromDays(1)); saslProvider.AddHandler(saslHandler); return(settings); }
public async Task RunSampleAsync() { Console.WriteLine($"Initializing the device provisioning client..."); using var security = new SecurityProviderSymmetricKey( this.id, this.key, null); using var transportHandler = new ProvisioningTransportHandlerAmqp(); ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( "global.azure-devices-provisioning.net", this.idScope, security, transportHandler); Console.WriteLine($"Initialized for registration Id {security.GetRegistrationID()}."); Console.WriteLine("Registering with the device provisioning service..."); DeviceRegistrationResult device = await provClient.RegisterAsync(); Console.WriteLine($"Registration status: {device.Status}."); if (device.Status != ProvisioningRegistrationStatusType.Assigned) { Console.WriteLine($"Registration status did not assign a hub, so exiting this sample."); return; } Console.WriteLine($"Device {device.DeviceId} registered to {device.AssignedHub}."); Console.WriteLine("Creating symmetric key authentication for IoT Hub..."); IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey( device.DeviceId, security.GetPrimaryKey()); await SendDeviceToCloudMessagesAsync(device, auth); Console.WriteLine("Finished."); }
public static async Task <DevicePortalInfoModel> ProvisionDeviceAsync(DeviceModel device) { try { using (var security = new SecurityProviderSymmetricKey(device.RegistrationId, device.PrimaryKey, device.SecondaryKey)) { using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly)) { ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, device.ID_Scope, security, transport); var result = await provClient.RegisterAsync(); if (result.Status != ProvisioningRegistrationStatusType.Assigned) { return(null); } IAuthenticationMethod auth = GetAuthenticationMethod(result, security); var host = $"{result.AssignedHub}"; var builder = IotHubConnectionStringBuilder.Create(host, auth); device.PrimaryKey = security.GetPrimaryKey(); device.SecondaryKey = security.GetSecondaryKey(); var o = new DevicePortalInfoModel { Host = host, Auth = auth, Device = device, ConnectionString = builder.ToString() }; return(o); } } } catch (Exception exp) { throw exp; } }
public async Task <IDevice> RegisterDevicesAsync(string deviceId) { var devicePrimaryKey = Utilities.ComputeDerivedSymmetricKey(Convert.FromBase64String(_dpsContext.PrimaryKey), deviceId); var deviceSecondaryKey = Utilities.ComputeDerivedSymmetricKey(Convert.FromBase64String(_dpsContext.SecondaryKey), deviceId); using (var security = new SecurityProviderSymmetricKey(deviceId, devicePrimaryKey, deviceSecondaryKey)) { using (var transport = new ProvisioningTransportHandlerMqtt()) { Console.WriteLine($"Resgistering {deviceId}...."); var provisioningDeviceClient = ProvisioningDeviceClient.Create(_dpsContext.GlobalDeviceEndpoint, _dpsContext.ScopeId, security, transport); var result = await provisioningDeviceClient.RegisterAsync(); var device = new Device { Key = security.GetPrimaryKey(), DeviceId = result.DeviceId, AssignedHub = result.AssignedHub, Status = result.Status }; return(device); } } }
internal static async Task <DeviceClient> ProvisionDeviceWithSasKeyAsync(string scopeId, string deviceId, string deviceKey, string modelId, ILogger log) { using (var transport = new ProvisioningTransportHandlerMqtt()) { using (var security = new SecurityProviderSymmetricKey(deviceId, deviceKey, null)) { DeviceRegistrationResult provResult; var provClient = ProvisioningDeviceClient.Create("global.azure-devices-provisioning.net", scopeId, security, transport); if (!string.IsNullOrEmpty(modelId)) { provResult = await provClient.RegisterAsync(GetProvisionPayload(modelId)).ConfigureAwait(false); } else { provResult = await provClient.RegisterAsync().ConfigureAwait(false); } log.LogInformation($"Provioning Result. Status [{provResult.Status}] SubStatus [{provResult.Substatus}]"); if (provResult.Status == ProvisioningRegistrationStatusType.Assigned) { log.LogWarning($"Device {provResult.DeviceId} in Hub {provResult.AssignedHub}"); log.LogInformation($"LastRefresh {provResult.LastUpdatedDateTimeUtc} RegistrationId {provResult.RegistrationId}"); var csBuilder = IotHubConnectionStringBuilder.Create(provResult.AssignedHub, new DeviceAuthenticationWithRegistrySymmetricKey(provResult.DeviceId, security.GetPrimaryKey())); string connectionString = csBuilder.ToString(); return(await Task.FromResult( DeviceClient.CreateFromConnectionString( connectionString, TransportType.Mqtt, new ClientOptions() { ModelId = modelId }))); } else { string errorMessage = $"Device not provisioned. Message: {provResult.ErrorMessage}"; log.LogError(errorMessage); throw new IotHubException(errorMessage); } } } }
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.SymmetricKey) { _dpsSettings.GroupEnrollment.SymmetricKeySettings.PrimaryKey = ProvisioningTools.ComputeDerivedSymmetricKey(_dpsSettings.GroupEnrollment.SymmetricKeySettings.PrimaryKey, _deviceSettingsDelegate.CurrentValue.DeviceId); } } _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Initializing the device provisioning client..."); // For individual enrollments, the first parameter must be the registration Id, where in the enrollment // the device Id is already chosen. However, for group enrollments the device Id can be requested by // the device, as long as the key has been computed using that value. // Also, the secondary could could be included, but was left out for the simplicity of this sample. using (var security = new SecurityProviderSymmetricKey(_deviceSettingsDelegate.CurrentValue.DeviceId, _dpsSettings.GroupEnrollment.SymmetricKeySettings.PrimaryKey, null)) { using (var transportHandler = ProvisioningTools.GetTransportHandler(_dpsSettings.GroupEnrollment.SymmetricKeySettings.TransportType)) { ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( _dpsSettings.GroupEnrollment.SymmetricKeySettings.GlobalDeviceEndpoint, _dpsSettings.GroupEnrollment.SymmetricKeySettings.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 symmetric key authentication for IoT Hub..."); var devicePrimaryKey = security.GetPrimaryKey(); //IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(deviceRegistrationResult.DeviceId, devicePrimaryKey); //_logger.LogDebug($"{logPrefix}::{_deviceSettings.ArtifactId}::Testing the provisioned device with IoT Hub..."); //using (DeviceClient iotClient = DeviceClient.Create(deviceRegistrationResult.AssignedHub, auth, _dpsSettings.GroupEnrollment.SymmetricKeySettings.TransportType)) //{ // _logger.LogDebug($"{logPrefix}::{_deviceSettings.ArtifactId}::Sending a telemetry message after provisioning to test the process..."); // using var message = new Message(Encoding.UTF8.GetBytes("TestMessage")); // await iotClient.SendEventAsync(message); // _logger.LogDebug($"{logPrefix}::{_deviceSettings.ArtifactId}::Finished."); //} result = $"HostName={deviceRegistrationResult.AssignedHub};DeviceId={deviceRegistrationResult.DeviceId};SharedAccessKey={devicePrimaryKey}"; } } else { _logger.LogError($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::No provisioning result has been received."); } } } return(result); }
public static DeviceClient CreateDeviceClient(Device dev) { using var security = new SecurityProviderSymmetricKey(dev.IoTDeviceId, dev.IoTDevicePrimaryKey, null); var result = RegisterDeviceAsync(security, dev).GetAwaiter().GetResult(); if (result.Status != ProvisioningRegistrationStatusType.Assigned) { Console.WriteLine("Failed to register device"); return(null); } IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, security.GetPrimaryKey()); return(DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt)); }
// Connect to IoT Hub/Central and send a test message private static async Task ConnectAndSend(DeviceProvisioningProxySettings settings) { // Configure DPS Transport Proxy var transport = new ProvisioningTransportHandlerHttp(); transport.Proxy = new WebProxy(settings.ProxyUri); // Create DPS Client var security = new SecurityProviderSymmetricKey(settings.RegistrationId, settings.PrimaryKey, settings.SecondaryKey); var provisioningClient = ProvisioningDeviceClient.Create(settings.GlobalDeviceEndpoint, settings.IdScope, security, transport); // Register Device var registrationResult = await provisioningClient.RegisterAsync().ConfigureAwait(false); // Configure Device Authentication from result var auth = new DeviceAuthenticationWithRegistrySymmetricKey(registrationResult.DeviceId, security.GetPrimaryKey()); // Configure IoT Hub/Central Proxy Http1TransportSettings transportSettings = new Http1TransportSettings(); transportSettings.Proxy = new WebProxy(settings.ProxyUri); ITransportSettings[] transportSettingsArray = new ITransportSettings[] { transportSettings }; // Connect to IoT Hub/Central and send a message var messageText = "{ \"test\": \"hello\" }"; var message = new Message(Encoding.UTF8.GetBytes(messageText)); using (var deviceClient = DeviceClient.Create(registrationResult.AssignedHub, auth, transportSettingsArray)) { try { await deviceClient.SendEventAsync(message); Console.WriteLine("Message sent"); } finally { Console.WriteLine("Done"); } } }
public async Task <IoTHubDeviceClient> ProvisionDeviceAsync() { string connectionKey; IoTHubDeviceClient iotHubClient = null; Console.WriteLine("Provisioning..."); if (!String.IsNullOrEmpty(_deviceId) && !String.IsNullOrEmpty(s_sasKey) && !String.IsNullOrEmpty(s_idScope)) { connectionKey = GenerateSymmetricKey(); Console.WriteLine($"Connection Key : {connectionKey}"); using (var securityProvider = new SecurityProviderSymmetricKey(_deviceId, connectionKey, null)) using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly)) { _provClient = ProvisioningDeviceClient.Create(s_global_endpoint, s_idScope, securityProvider, transport); // Sanity check Console.WriteLine($"Device ID : {securityProvider.GetRegistrationID()}"); DeviceRegistrationResult result = await _provClient.RegisterAsync().ConfigureAwait(false); if (result.Status == ProvisioningRegistrationStatusType.Assigned) { Console.WriteLine($"Provisioned : {result.Status}"); Console.WriteLine($" Device ID : {result.DeviceId}"); Console.WriteLine($" IoT Hub : {result.AssignedHub}"); IAuthenticationMethod authenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, securityProvider.GetPrimaryKey()); iotHubClient = new IoTHubDeviceClient(result.AssignedHub, authenticationMethod); } else { Console.WriteLine($"Err : Provisioning Failed {result.Status}"); } } } else { Console.WriteLine("Please set following Environment Variables"); Console.WriteLine("DPS_IDSCOPE : ID Scope"); Console.WriteLine("SAS_KEY : SAS Key"); } return(iotHubClient); }
public IAuthenticationMethod Create() { return(new DeviceAuthenticationWithRegistrySymmetricKey( _deviceRegistrationProvider.DeviceId, _securityProvider.GetPrimaryKey())); }