public async Task ProvisioningServiceClient_GetIndividualEnrollmentAttestation(AttestationMechanismType attestationType) { using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString); string registrationId = AttestationTypeToString(attestationType) + "-" + Guid.NewGuid(); IndividualEnrollment individualEnrollment = await CreateIndividualEnrollmentAsync( provisioningServiceClient, registrationId, attestationType, null, null, AllocationPolicy.Static, null, null, null, Logger) .ConfigureAwait(false); AttestationMechanism attestationMechanism = null; await RetryOperationHelper .RetryOperationsAsync( async() => { attestationMechanism = await provisioningServiceClient.GetIndividualEnrollmentAttestationAsync(individualEnrollment.RegistrationId); }, s_provisioningServiceRetryPolicy, s_retryableExceptions, Logger) .ConfigureAwait(false); if (attestationMechanism == null) { throw new ArgumentException($"The attestation mechanism for enrollment with registration Id {individualEnrollment.RegistrationId} could not retrieved, exiting test."); } if (attestationType == AttestationMechanismType.SymmetricKey) { attestationMechanism.Type.Should().Be(AttestationMechanismType.SymmetricKey); var symmetricKeyAttestation = (SymmetricKeyAttestation)attestationMechanism.GetAttestation(); symmetricKeyAttestation.PrimaryKey.Should().Be(((SymmetricKeyAttestation)individualEnrollment.Attestation).PrimaryKey); symmetricKeyAttestation.SecondaryKey.Should().Be(((SymmetricKeyAttestation)individualEnrollment.Attestation).SecondaryKey); } else if (attestationType == AttestationMechanismType.X509) { attestationMechanism.Type.Should().Be(AttestationMechanismType.X509); var x509Attestation = (X509Attestation)attestationMechanism.GetAttestation(); x509Attestation.GetPrimaryX509CertificateInfo().SHA1Thumbprint.Should().Be(((X509Attestation)individualEnrollment.Attestation).GetPrimaryX509CertificateInfo().SHA1Thumbprint); x509Attestation.GetSecondaryX509CertificateInfo().SHA1Thumbprint.Should().Be(((X509Attestation)individualEnrollment.Attestation).GetSecondaryX509CertificateInfo().SHA1Thumbprint); } else { attestationMechanism.Type.Should().Be(AttestationMechanismType.Tpm); var tpmAttestation = (TpmAttestation)attestationMechanism.GetAttestation(); tpmAttestation.EndorsementKey.Should().Be(((TpmAttestation)individualEnrollment.Attestation).EndorsementKey); tpmAttestation.StorageRootKey.Should().Be(((TpmAttestation)individualEnrollment.Attestation).StorageRootKey); } }
public static PSIndividualEnrollment ToPSIndividualEnrollment(IndividualEnrollment enrollment) { PSIndividualEnrollment psIndividualEnrollment = ConvertObject <IndividualEnrollment, PSIndividualEnrollment>(enrollment); psIndividualEnrollment.Attestation = GetAttestationMechanism(enrollment); return(psIndividualEnrollment); }
public static async Task ProvisioningServiceClient_IndividualEnrollments_Create_Ok(string proxyServerAddress, AttestationMechanismType attestationType, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection<string> iotHubsToProvisionTo) { using (ProvisioningServiceClient provisioningServiceClient = CreateProvisioningService(proxyServerAddress)) { IndividualEnrollment individualEnrollment = await CreateIndividualEnrollment(provisioningServiceClient, attestationType, reprovisionPolicy, allocationPolicy, customAllocationDefinition, iotHubsToProvisionTo, null).ConfigureAwait(false); IndividualEnrollment individualEnrollmentResult = await provisioningServiceClient.GetIndividualEnrollmentAsync(individualEnrollment.RegistrationId).ConfigureAwait(false); Assert.AreEqual(individualEnrollmentResult.ProvisioningStatus, ProvisioningStatus.Enabled); if (reprovisionPolicy != null) { Assert.AreEqual(reprovisionPolicy.UpdateHubAssignment, individualEnrollmentResult.ReprovisionPolicy.UpdateHubAssignment); Assert.AreEqual(reprovisionPolicy.MigrateDeviceData, individualEnrollmentResult.ReprovisionPolicy.MigrateDeviceData); } if (customAllocationDefinition != null) { Assert.AreEqual(customAllocationDefinition.WebhookUrl, individualEnrollmentResult.CustomAllocationDefinition.WebhookUrl); Assert.AreEqual(customAllocationDefinition.ApiVersion, individualEnrollmentResult.CustomAllocationDefinition.ApiVersion); } //allocation policy is never null Assert.AreEqual(allocationPolicy, individualEnrollmentResult.AllocationPolicy); await provisioningServiceClient.DeleteIndividualEnrollmentAsync(individualEnrollment.RegistrationId).ConfigureAwait(false); } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string name = req.Query["deviceid"]; string primaryKey = ""; var credential = new ChainedTokenCredential( new ManagedIdentityCredential(), new VisualStudioCodeCredential()); var client = new SecretClient(new Uri("https://deviceonboardingkeyvault.vault.azure.net/"), credential); var secret = client.GetSecret("dpsconnectionstring"); using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(secret.Value.Value)){ var attestation = new SymmetricKeyAttestation("", ""); var ie = new IndividualEnrollment(name, attestation); var enrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(ie); var keys = enrollment.Attestation as SymmetricKeyAttestation; primaryKey = keys.PrimaryKey; log.LogInformation(enrollment.IotHubHostName); } return(new OkObjectResult(primaryKey)); }
public static PSAttestation GetAttestationMechanism(IndividualEnrollment enrollment) { if (enrollment.Attestation.GetType().Name.Equals("SymmetricKeyAttestation", StringComparison.OrdinalIgnoreCase)) { return(new PSAttestation() { Type = PSAttestationMechanismType.SymmetricKey, SymmetricKey = (SymmetricKeyAttestation)enrollment.Attestation }); } else if (enrollment.Attestation.GetType().Name.Equals("X509Attestation", StringComparison.OrdinalIgnoreCase)) { return(new PSAttestation() { Type = PSAttestationMechanismType.X509, X509 = (X509Attestation)enrollment.Attestation }); } else if (enrollment.Attestation.GetType().Name.Equals("TpmAttestation", StringComparison.OrdinalIgnoreCase)) { return(new PSAttestation() { Type = PSAttestationMechanismType.Tpm, Tpm = (TpmAttestation)enrollment.Attestation }); } else { throw new ProvisioningServiceClientException("Unknown Attestation type"); } }
private static async Task <IndividualEnrollment> EnrollToDpsAsync(string primaryKey, string secondKey, string registeredId, string provisionConnString) { using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(ProvisionConnString); IndividualEnrollment device = null; try { device = await provisioningServiceClient.GetIndividualEnrollmentAsync(registeredId).ConfigureAwait(false); } catch (ProvisioningServiceClientException ex) { // device is not existed } // if device is not existed, create device in DPS if (device == null) { Attestation attestation = new SymmetricKeyAttestation(primaryKey, secondKey); var individualEnrollment = new IndividualEnrollment( registeredId, attestation) { // TODO check device id region and set region IoTHub service host name IotHubHostName = "connect-iothub-dev.azure-devices.net" }; device = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment); } return(device); }
/********************************************************************************** * Retrive Individual Enrollment from DPS *********************************************************************************/ public async Task <IndividualEnrollment> GetDpsEnrollment(string registrationId) { IndividualEnrollment enrollment = null; try { QuerySpecification querySpecification = new QuerySpecification("SELECT * FROM enrollments"); using (Query query = _provisioningServiceClient.CreateIndividualEnrollmentQuery(querySpecification)) { while (query.HasNext() && enrollment == null) { QueryResult queryResults = await query.NextAsync().ConfigureAwait(false); foreach (IndividualEnrollment item in queryResults.Items) { _logger.LogInformation($"GetDpsEnrollment found enrollment : {item}"); if (item.RegistrationId.Equals(registrationId)) { enrollment = item; break; } } } } } catch (Exception e) { _logger.LogError($"Exception in GetDpsEnrollment() : {e.Message}"); } return(enrollment); }
/********************************************************************************** * Add a new individual enrollment *********************************************************************************/ public async Task <bool> AddDpsEnrollment(string newRegistrationId) { bool bCreated = false; string primaryKey = ""; string secondaryKey = ""; try { Attestation attestation = new SymmetricKeyAttestation(primaryKey, secondaryKey); IndividualEnrollment individualEnrollment = new IndividualEnrollment(newRegistrationId, attestation); individualEnrollment.DeviceId = newRegistrationId; if (!string.IsNullOrEmpty(_dps_webhookUrl)) { individualEnrollment.CustomAllocationDefinition = new CustomAllocationDefinition() { WebhookUrl = _dps_webhookUrl, ApiVersion = "2019-03-31" }; individualEnrollment.AllocationPolicy = AllocationPolicy.Custom; } var newEnrollment = await _provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); bCreated = true; } //catch (DeviceAlreadyExistsException) //{ //} catch (Exception e) { _logger.LogError($"Exception in GetDpsEnrollment() : {e.Message}"); } return(bCreated); }
public static async Task <bool> RegisterDevice(string deviceId, string deviceName) { if (String.IsNullOrEmpty(deviceId)) { return(false); } Console.WriteLine("Starting SetRegistrationData"); Attestation attestation = new TpmAttestation(SampleTpmEndorsementKey); IndividualEnrollment individualEnrollment = new IndividualEnrollment(deviceName, attestation); individualEnrollment.DeviceId = deviceId; individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus; Console.WriteLine("\nAdding new individualEnrollment..."); var serviceClient = GetProvisioningServiceClient(); IndividualEnrollment individualEnrollmentResult = await serviceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); Console.WriteLine("\nIndividualEnrollment created with success."); Console.WriteLine(individualEnrollmentResult); return(true); }
private static async Task EnrollDeviceInDpsAsync(string dpsConnectionString, string registrationId, string tpmEndorsementKey, string deviceId) { using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(dpsConnectionString)) { Console.WriteLine("\nCreating a new individualEnrollment..."); var attestation = new TpmAttestation(tpmEndorsementKey); var individualEnrollment = new IndividualEnrollment(registrationId.ToLower(), attestation); // The following parameters are optional. Remove them if you don't need them. individualEnrollment.DeviceId = deviceId; // Add this line if you deploy an IoT Edge device individualEnrollment.Capabilities = new DeviceCapabilities { IotEdge = true }; individualEnrollment.ProvisioningStatus = ProvisioningStatus.Enabled; Console.WriteLine("\nAdding new individualEnrollment..."); var individualEnrollmentResult = await provisioningServiceClient. CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment) .ConfigureAwait(false); Console.WriteLine("\nIndividualEnrollment created with success."); Console.WriteLine(individualEnrollmentResult); } }
public async Task CreateIndividualEnrollmentTpmAsync() { Console.WriteLine("\nCreating a new individualEnrollment..."); Attestation attestation = new TpmAttestation(TpmEndorsementKey); IndividualEnrollment individualEnrollment = new IndividualEnrollment( RegistrationId, attestation); // The following parameters are optional: individualEnrollment.DeviceId = OptionalDeviceId; individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus; individualEnrollment.InitialTwinState = new TwinState( null, new TwinCollection() { ["Brand"] = "Contoso", ["Model"] = "SSC4", ["Color"] = "White", }); individualEnrollment.Capabilities = OptionalEdgeCapabilityEnabled; Console.WriteLine("\nAdding new individualEnrollment..."); IndividualEnrollment individualEnrollmentResult = await _provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); Console.WriteLine(individualEnrollmentResult); }
public async Task ProvisioningServiceClient_GetIndividualEnrollmentAttestation(AttestationMechanismType attestationType) { ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString); IndividualEnrollment individualEnrollment = await CreateIndividualEnrollment(provisioningServiceClient, attestationType, null, AllocationPolicy.Static, null, null, null); AttestationMechanism attestationMechanism = await provisioningServiceClient.GetIndividualEnrollmentAttestationAsync(individualEnrollment.RegistrationId); if (attestationType == AttestationMechanismType.SymmetricKey) { Assert.AreEqual(AttestationMechanismType.SymmetricKey, attestationMechanism.Type); SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation)attestationMechanism.GetAttestation(); Assert.AreEqual(((SymmetricKeyAttestation)individualEnrollment.Attestation).PrimaryKey, symmetricKeyAttestation.PrimaryKey); Assert.AreEqual(((SymmetricKeyAttestation)individualEnrollment.Attestation).SecondaryKey, symmetricKeyAttestation.SecondaryKey); } else if (attestationType == AttestationMechanismType.X509) { Assert.AreEqual(AttestationMechanismType.X509, attestationMechanism.Type); X509Attestation x509Attestation = (X509Attestation)attestationMechanism.GetAttestation(); Assert.AreEqual(((X509Attestation)individualEnrollment.Attestation).GetPrimaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetPrimaryX509CertificateInfo().SHA1Thumbprint); Assert.AreEqual(((X509Attestation)individualEnrollment.Attestation).GetSecondaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetSecondaryX509CertificateInfo().SHA1Thumbprint); } else { Assert.AreEqual(AttestationMechanismType.Tpm, attestationMechanism.Type); TpmAttestation tpmAttestation = (TpmAttestation)attestationMechanism.GetAttestation(); Assert.AreEqual(((TpmAttestation)individualEnrollment.Attestation).EndorsementKey, tpmAttestation.EndorsementKey); Assert.AreEqual(((TpmAttestation)individualEnrollment.Attestation).StorageRootKey, tpmAttestation.StorageRootKey); } }
public void IndividualEnrollmentConstructorJSONSucceedOnMinumum() { // arrange string minJson = "{\n" + " \"registrationId\":\"" + SampleRegistrationId + "\",\n" + " \"attestation\":{\n" + " \"type\":\"x509\",\n" + " \"x509\":{\n" + " \"clientCertificates\":{\n" + " \"primary\":{\n" + " \"info\": {\n" + " \"subjectName\": \"CN=ROOT_00000000-0000-0000-0000-000000000000, OU=Azure IoT, O=MSFT, C=US\",\n" + " \"sha1Thumbprint\": \"0000000000000000000000000000000000\",\n" + " \"sha256Thumbprint\": \"" + SampleRegistrationId + "\",\n" + " \"issuerName\": \"CN=ROOT_00000000-0000-0000-0000-000000000000, OU=Azure IoT, O=MSFT, C=US\",\n" + " \"notBeforeUtc\": \"2017-11-14T12:34:18Z\",\n" + " \"notAfterUtc\": \"2017-11-20T12:34:18Z\",\n" + " \"serialNumber\": \"000000000000000000\",\n" + " \"version\": 3\n" + " }\n" + " }\n" + " }\n" + " }\n" + " },\n" + " \"etag\": \"" + SampleEtag + "\"\n" + "}"; IndividualEnrollment individualEnrollment = Newtonsoft.Json.JsonConvert.DeserializeObject <IndividualEnrollment>(minJson); // act - assert Assert.IsNotNull(individualEnrollment); Assert.AreEqual(SampleRegistrationId, individualEnrollment.RegistrationId); Assert.IsTrue(individualEnrollment.Attestation is X509Attestation); Assert.AreEqual(SampleEtag, individualEnrollment.ETag); }
public static async Task RunSample() { Console.WriteLine("Starting sample..."); using (ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(ProvisioningConnectionString)) { #region Create a new individualEnrollment config Console.WriteLine("\nCreating a new individualEnrollment..."); Attestation attestation = new TpmAttestation(TpmEndorsementKey); IndividualEnrollment individualEnrollment = new IndividualEnrollment( RegistrationId, attestation); #endregion #region Create the individualEnrollment Console.WriteLine("\nAdding new individualEnrollment..."); IndividualEnrollment individualEnrollmentResult = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); Console.WriteLine("\nIndividualEnrollment created with success."); Console.WriteLine(individualEnrollmentResult); #endregion } }
private static async Task CreateOrUpdateIndividualEnrollmentAsync() { try { using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(dpsConnectionString)) { Console.WriteLine("Connected to sample provisioning service successfully."); // Create a new individualEnrollment config Console.WriteLine(); Attestation attestation = new TpmAttestation(tpmEndorsementKey); IndividualEnrollment individualEnrollment = new IndividualEnrollment(registrationId, attestation) { DeviceId = optionalDeviceId, ProvisioningStatus = optionalProvisioningStatus }; // Create the individualEnrollment Console.WriteLine("Adding new individualEnrollment..."); IndividualEnrollment individualEnrollmentResult = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); Console.WriteLine("IndividualEnrollment created :"); Console.WriteLine(individualEnrollmentResult); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); } }
public void IndividualEnrollmentConstructorSucceedOnX509Client() { // arrange - act IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, SampleX509ClientAttestation); // assert Assert.AreEqual(SampleRegistrationId, individualEnrollment.RegistrationId); Assert.AreEqual(SamplePublicKeyCertificateString, ((X509Attestation)individualEnrollment.Attestation).ClientCertificates.Primary.Certificate); }
public void IndividualEnrollmentConstructorSucceedOnX509CAReference() { // arrange - act IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, SampleX509CAReferenceAttestation); // assert Assert.AreEqual(SampleRegistrationId, individualEnrollment.RegistrationId); Assert.AreEqual(SampleCAReference, ((X509Attestation)individualEnrollment.Attestation).CAReferences.Primary); }
public void IndividualEnrollmentConstructorSucceedOnTPM() { // arrange - act IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, SampleTpmAttestation); // assert Assert.AreEqual(SampleRegistrationId, individualEnrollment.RegistrationId); Assert.AreEqual(SampleEndorsementKey, ((TpmAttestation)individualEnrollment.Attestation).EndorsementKey); }
public async Task <IndividualEnrollment> GetIndividualEnrollmentInfoAsync() { Console.WriteLine("\nGetting the individualEnrollment information..."); IndividualEnrollment getResult = await _provisioningServiceClient.GetIndividualEnrollmentAsync(RegistrationId).ConfigureAwait(false); Console.WriteLine(getResult); return(getResult); }
public static async Task RunSample() { Console.WriteLine("Starting sample..."); using (ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(_provisioningConnectionString)) { #region Create a new individualEnrollment config Console.WriteLine("\nCreating a new individualEnrollment..."); Attestation attestation = new TpmAttestation(_tpmEndorsementKey); IndividualEnrollment individualEnrollment = new IndividualEnrollment( SampleRegistrationId, attestation); // The following parameters are optional. Remove it if you don't need. individualEnrollment.DeviceId = OptionalDeviceId; individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus; #endregion #region Create the individualEnrollment Console.WriteLine("\nAdding new individualEnrollment..."); IndividualEnrollment individualEnrollmentResult = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); Console.WriteLine("\nIndividualEnrollment created with success."); Console.WriteLine(individualEnrollmentResult); #endregion #region Get info of individualEnrollment Console.WriteLine("\nGetting the individualEnrollment information..."); IndividualEnrollment getResult = await provisioningServiceClient.GetIndividualEnrollmentAsync(SampleRegistrationId).ConfigureAwait(false); Console.WriteLine(getResult); #endregion #region Query info of individualEnrollment Console.WriteLine("\nCreating a query for enrollments..."); QuerySpecification querySpecification = new QuerySpecification("SELECT * FROM enrollments"); using (Query query = provisioningServiceClient.CreateIndividualEnrollmentQuery(querySpecification)) { while (query.HasNext()) { Console.WriteLine("\nQuerying the next enrollments..."); QueryResult queryResult = await query.NextAsync().ConfigureAwait(false); Console.WriteLine(queryResult); } } #endregion #region Delete info of individualEnrollment Console.WriteLine("\nDeleting the individualEnrollment..."); await provisioningServiceClient.DeleteIndividualEnrollmentAsync(getResult).ConfigureAwait(false); #endregion } }
private async Task ProvisioningServiceClient_IndividualEnrollments_Create_Ok(string proxyServerAddress) { ProvisioningServiceClient provisioningServiceClient = CreateProvisioningServiceWithProxy(proxyServerAddress); IndividualEnrollment individualEnrollment = await CreateIndividualEnrollment(provisioningServiceClient).ConfigureAwait(false); IndividualEnrollment individualEnrollmentResult = await provisioningServiceClient.GetIndividualEnrollmentAsync(RegistrationId).ConfigureAwait(false); Assert.AreEqual(individualEnrollmentResult.ProvisioningStatus, ProvisioningStatus.Enabled); await provisioningServiceClient.DeleteIndividualEnrollmentAsync(RegistrationId).ConfigureAwait(false); }
public async Task UpdateIndividualEnrollmentAsync() { var individualEnrollment = await GetIndividualEnrollmentInfoAsync().ConfigureAwait(false); individualEnrollment.InitialTwinState.DesiredProperties["Color"] = "Yellow"; individualEnrollment.Capabilities = OptionalEdgeCapabilityDisabled; IndividualEnrollment individualEnrollmentResult = await _provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); Console.WriteLine(individualEnrollmentResult); }
public async Task GetIndividualEnrollmentInfoAsync(List <IndividualEnrollment> individualEnrollments) { foreach (IndividualEnrollment individualEnrollment in individualEnrollments) { String registrationId = individualEnrollment.RegistrationId; Console.WriteLine($"\nGetting the {nameof(individualEnrollment)} information for {registrationId}..."); IndividualEnrollment getResult = await _provisioningServiceClient.GetIndividualEnrollmentAsync(registrationId).ConfigureAwait(false); Console.WriteLine(getResult); } }
private async Task <IndividualEnrollment> CreateIndividualEnrollment(ProvisioningServiceClient provisioningServiceClient) { var tpmSim = new SecurityProviderTpmSimulator(Configuration.Provisioning.TpmDeviceRegistrationId); string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey()); var attestation = new TpmAttestation(base64Ek); IndividualEnrollment individualEnrollment = new IndividualEnrollment( RegistrationId, attestation); IndividualEnrollment result = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); return(result); }
static async Task SetRegistrationDataAsync() { #region QueryingEnrollemnts Console.WriteLine("Fetching Existing Enrollments--------------------------------"); using var serviceClient = ProvisioningServiceClient.CreateFromConnectionString(ServiceConnectionString); QuerySpecification qu = new QuerySpecification("SELECT * FROM enrollments"); using (Query query = serviceClient.CreateIndividualEnrollmentQuery(qu)) { while (query.HasNext()) { Console.WriteLine("\nQuerying the next enrollments..."); QueryResult queryResult = await query.NextAsync().ConfigureAwait(false); Console.WriteLine(queryResult); } } Console.WriteLine("Enrollment Fetch Complete------------------------------------"); #endregion #region CreateIndividualEnrollment Console.WriteLine("Starting SetRegistrationData"); //Attestation attestation = X509Attestation.CreateFromClientCertificates(privateKey); var pem = System.IO.File.ReadAllText(@"D:\Code\Diality\CACerts\CACertificates\mydevice4-public.pem"); string certBuffer = GetBytesFromPEM(pem, "CERTIFICATE"); Attestation attestation = X509Attestation.CreateFromClientCertificates(certBuffer); IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, attestation); individualEnrollment.DeviceId = OptionalDeviceId; individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus; individualEnrollment.IotHubHostName = "vvk5cob-Iot-Hub-2.azure-devices.net"; Console.WriteLine("\nAdding new individualEnrollment..."); IndividualEnrollment individualEnrollmentResult = await serviceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); Console.WriteLine("\nIndividualEnrollment created with success."); Console.WriteLine(individualEnrollmentResult); #endregion }
public async Task CreateIndividualEnrollment( string individualEnrollmentId, X509Certificate2 enrollmentCertificate) { _logger.LogInformation("Starting CreateIndividualEnrollment..."); using (ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString( Configuration.GetConnectionString("DpsConnection"))) { _logger.LogInformation("Creating a new individualEnrollment..."); Attestation attestation = X509Attestation.CreateFromClientCertificates(enrollmentCertificate); //IndividualEnrollment individualEnrollment = // new IndividualEnrollment( // IndividualEnrollmentId, // attestation); IndividualEnrollment individualEnrollment = new IndividualEnrollment(individualEnrollmentId, attestation) { ProvisioningStatus = ProvisioningStatus.Enabled, DeviceId = individualEnrollmentId, Capabilities = new Microsoft.Azure.Devices.Shared.DeviceCapabilities { IotEdge = true }, InitialTwinState = new TwinState( new Microsoft.Azure.Devices.Shared.TwinCollection("{ \"updatedby\":\"" + "damien" + "\", \"timeZone\":\"" + TimeZoneInfo.Local.DisplayName + "\" }"), new Microsoft.Azure.Devices.Shared.TwinCollection("{}") ), ReprovisionPolicy = new ReprovisionPolicy { MigrateDeviceData = false, UpdateHubAssignment = true } }; _logger.LogInformation($"{individualEnrollment}"); _logger.LogInformation("Adding new individualEnrollment..."); var individualEnrollmentResult = await provisioningServiceClient .CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment) .ConfigureAwait(false); _logger.LogInformation("EnrollmentGroup created with success."); _logger.LogInformation($"{individualEnrollmentResult}"); } }
private async Task <SecurityProvider> CreateSecurityProviderFromName(string name, X509EnrollmentType?x509Type) { _verboseLog.WriteLine($"{nameof(CreateSecurityProviderFromName)}({name})"); switch (name) { case nameof(SecurityProviderTpmHsm): var tpmSim = new SecurityProviderTpmSimulator(Configuration.Provisioning.TpmDeviceRegistrationId); string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey()); string registrationId = Configuration.Provisioning.TpmDeviceRegistrationId; var provisioningService = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString); _log.WriteLine($"Getting enrollment: RegistrationID = {registrationId}"); IndividualEnrollment enrollment = await provisioningService.GetIndividualEnrollmentAsync(registrationId).ConfigureAwait(false); var attestation = new TpmAttestation(base64Ek); enrollment.Attestation = attestation; _log.WriteLine($"Updating enrollment: RegistrationID = {registrationId} EK = '{base64Ek}'"); await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(enrollment).ConfigureAwait(false); return(tpmSim); case nameof(SecurityProviderX509Certificate): X509Certificate2 certificate = null; X509Certificate2Collection collection = null; switch (x509Type) { case X509EnrollmentType.Individual: certificate = Configuration.Provisioning.GetIndividualEnrollmentCertificate(); break; case X509EnrollmentType.Group: certificate = Configuration.Provisioning.GetGroupEnrollmentCertificate(); collection = Configuration.Provisioning.GetGroupEnrollmentChain(); break; default: throw new NotSupportedException($"Unknown X509 type: '{x509Type}'"); } return(new SecurityProviderX509Certificate(certificate, collection)); } throw new NotSupportedException($"Unknown security type: '{name}'."); }
public static async Task <IndividualEnrollment> CreateIndividualEnrollment(ProvisioningServiceClient provisioningServiceClient, AttestationType attestationType, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection <string> iotHubsToProvisionTo, DeviceCapabilities capabilities) { string registrationId = AttestationTypeToString(attestationType) + "-registration-id-" + Guid.NewGuid(); Attestation attestation; IndividualEnrollment individualEnrollment; switch (attestationType) { case AttestationType.Tpm: using (var tpmSim = new SecurityProviderTpmSimulator(registrationId)) { string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey()); var provisioningService = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString); individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek)) { Capabilities = capabilities, AllocationPolicy = allocationPolicy, ReprovisionPolicy = reprovisionPolicy, CustomAllocationDefinition = customAllocationDefinition, IotHubs = iotHubsToProvisionTo }; IndividualEnrollment enrollment = await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); attestation = new TpmAttestation(base64Ek); enrollment.Attestation = attestation; return(await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(enrollment).ConfigureAwait(false)); } case AttestationType.SymmetricKey: string primaryKey = CryptoKeyGenerator.GenerateKey(32); string secondaryKey = CryptoKeyGenerator.GenerateKey(32); attestation = new SymmetricKeyAttestation(primaryKey, secondaryKey); break; case AttestationType.x509: default: throw new NotSupportedException("Test code has not been written for testing this attestation type yet"); } individualEnrollment = new IndividualEnrollment(registrationId, attestation); individualEnrollment.Capabilities = capabilities; individualEnrollment.CustomAllocationDefinition = customAllocationDefinition; individualEnrollment.ReprovisionPolicy = reprovisionPolicy; individualEnrollment.IotHubs = iotHubsToProvisionTo; individualEnrollment.AllocationPolicy = allocationPolicy; return(await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false)); }
public void IndividualEnrollmentConstructorJSONSucceed() { // arrange IndividualEnrollment individualEnrollment = Newtonsoft.Json.JsonConvert.DeserializeObject <IndividualEnrollment>(SampleIndividualEnrollmentJson); // act - assert Assert.IsNotNull(individualEnrollment); Assert.AreEqual(SampleRegistrationId, individualEnrollment.RegistrationId); Assert.IsTrue(individualEnrollment.Attestation is X509Attestation); Assert.AreEqual(SampleDeviceId, individualEnrollment.DeviceId); Assert.AreEqual(SampleIotHubHostName, individualEnrollment.IotHubHostName); Assert.IsNotNull(individualEnrollment.InitialTwinState); Assert.AreEqual(SampleProvisioningStatus, individualEnrollment.ProvisioningStatus); Assert.AreEqual(SampleCreateDateTimeUTC, individualEnrollment.CreatedDateTimeUtc); Assert.AreEqual(SampleLastUpdatedDateTimeUTC, individualEnrollment.LastUpdatedDateTimeUtc); Assert.AreEqual(SampleEtag, individualEnrollment.ETag); }
/// <summary> /// Update the enrollment under test such that it forces it to reprovision to the hubs within <paramref name="iotHubsToReprovisionTo"/> /// </summary> private async Task UpdateEnrollmentToForceReprovision(EnrollmentType?enrollmentType, ProvisioningServiceClient provisioningServiceClient, ICollection <String> iotHubsToReprovisionTo, SecurityProvider security, string groupId) { if (enrollmentType == EnrollmentType.Individual) { IndividualEnrollment individualEnrollment = await provisioningServiceClient.GetIndividualEnrollmentAsync(security.GetRegistrationID()).ConfigureAwait(false); individualEnrollment.IotHubs = iotHubsToReprovisionTo; IndividualEnrollment individualEnrollmentResult = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false); } else { EnrollmentGroup enrollmentGroup = await provisioningServiceClient.GetEnrollmentGroupAsync(groupId).ConfigureAwait(false); enrollmentGroup.IotHubs = iotHubsToReprovisionTo; EnrollmentGroup enrollmentGroupResult = await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false); } }