Exemple #1
0
        public async Task ListCertificatesAsync()
        {
            #region Snippet:ListCertificatesAsync
            AsyncPageable <CertificateProperties> allCertificates = client.GetPropertiesOfCertificatesAsync();

            await foreach (CertificateProperties certificateProperties in allCertificates)
            {
                Console.WriteLine(certificateProperties.Name);
            }
            #endregion
        }
Exemple #2
0
        public async IAsyncEnumerable <CertRef> GetCertRefsAsync()
        {
            var client = new CertificateClient(_kvUri, _cred);
            var certs  = client.GetPropertiesOfCertificatesAsync();

            await foreach (var cert in certs)
            {
                yield return(new CertRef {
                    Name = cert.Name
                });
            }
        }
        public async Task <IReadOnlyList <CertificateItem> > GetExpiringCertificates([ActivityTrigger] DateTime currentDateTime)
        {
            var certificates = _certificateClient.GetPropertiesOfCertificatesAsync();

            var result = new List <CertificateItem>();

            await foreach (var certificate in certificates)
            {
                if (!certificate.TagsFilter(IssuerName, _options.Endpoint))
                {
                    continue;
                }

                if ((certificate.ExpiresOn.Value - currentDateTime).TotalDays > 30)
                {
                    continue;
                }

                result.Add((await _certificateClient.GetCertificateAsync(certificate.Name)).Value.ToCertificateItem());
            }

            return(result);
        }
Exemple #4
0
        public async Task <List <CertificateModel> > GetCertificatesInVaultAsync(Uri vaultUri)
        {
            var totalItems = new List <CertificateProperties>();

            var certClient = new CertificateClient(vaultUri, appTokenCredential);
            var certs      = certClient.GetPropertiesOfCertificatesAsync(includePending: true).ConfigureAwait(false);

            await foreach (var cert in certs)
            {
                totalItems.Add(cert);
            }

            var models = totalItems
                         .Select(ci => new CertificateModel
            {
                Name = ci.Name,
                CertificateIdentifier = ci.Id,
                Thumbprint            = ci.X509Thumbprint != null ? BitConverter.ToString(ci.X509Thumbprint).Replace("-", "") : null,
                Attributes            = ci
            }).ToList();


            return(models.OrderBy(cm => cm.Name).ToList());
        }
        public async Task GetCertificatesAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a certificate client that will be used to call the service. Notice that the client is using default Azure
            // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create two self-signed certificates using the default policy
            string certName1 = $"defaultCert-{Guid.NewGuid()}";

            CertificateOperation certOp1 = await client.StartCreateCertificateAsync(certName1, CertificatePolicy.Default);

            string certName2 = $"defaultCert-{Guid.NewGuid()}";

            CertificateOperation certOp2 = await client.StartCreateCertificateAsync(certName1, CertificatePolicy.Default);

            // Next, let's wait on the certificate operation to complete. Note that certificate creation can last an indeterministic
            // amount of time, so applications should only wait on the operation to complete in the case the issuance time is well
            // known and within the scope of the application lifetime. In this case we are creating a self-signed certificate which
            // should be issued in a relatively short amount of time.
            await certOp1.WaitForCompletionAsync();

            await certOp2.WaitForCompletionAsync();

            // Let's list the certificates which exist in the vault along with their thumbprints
            await foreach (CertificateProperties cert in client.GetPropertiesOfCertificatesAsync())
            {
                Debug.WriteLine($"Certificate is returned with name {cert.Name} and thumbprint {BitConverter.ToString(cert.X509Thumbprint)}");
            }

            // We need to create a new version of a certificate. Creating a certificate with the same name will create another version of the certificate
            CertificateOperation newCertOp = await client.StartCreateCertificateAsync(certName1, CertificatePolicy.Default);

            await newCertOp.WaitForCompletionAsync();

            // Let's print all the versions of this certificate
            await foreach (CertificateProperties cert in client.GetPropertiesOfCertificateVersionsAsync(certName1))
            {
                Debug.WriteLine($"Certificate {cert.Name} with name {cert.Version}");
            }

            // The certificates are no longer needed.
            // You need to delete them from the Key Vault.
            DeleteCertificateOperation operation1 = await client.StartDeleteCertificateAsync(certName1);

            DeleteCertificateOperation operation2 = await client.StartDeleteCertificateAsync(certName2);

            // To ensure certificates are deleted on server side.
            Task.WaitAll(
                operation1.WaitForCompletionAsync().AsTask(),
                operation2.WaitForCompletionAsync().AsTask());

            // You can list all the deleted and non-purged certificates, assuming Key Vault is soft-delete enabled.
            await foreach (DeletedCertificate deletedCert in client.GetDeletedCertificatesAsync())
            {
                Debug.WriteLine($"Deleted certificate's recovery Id {deletedCert.RecoveryId}");
            }

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged.
            Task.WaitAll(
                client.PurgeDeletedCertificateAsync(certName1),
                client.PurgeDeletedCertificateAsync(certName2));
        }
Exemple #6
0
        private async Task MigrationGuide()
        {
            #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_Create
            CertificateClient client = new CertificateClient(
                new Uri("https://myvault.vault.azure.net"),
                new DefaultAzureCredential());
            #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_Create

            #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions
            using (HttpClient httpClient = new HttpClient())
            {
                CertificateClientOptions options = new CertificateClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                };

                //@@CertificateClient client = new CertificateClient(
                /*@@*/ CertificateClient _ = new CertificateClient(
                    new Uri("https://myvault.vault.azure.net"),
                    new DefaultAzureCredential(),
                    options);
            }
            #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions

            #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateCustomPolicy
            CertificatePolicy policy = new CertificatePolicy("issuer-name", "CN=customdomain.com")
            {
                ContentType = CertificateContentType.Pkcs12,
                KeyType     = CertificateKeyType.Rsa,
                ReuseKey    = true,
                KeyUsage    =
                {
                    CertificateKeyUsage.CrlSign,
                    CertificateKeyUsage.DataEncipherment,
                    CertificateKeyUsage.DigitalSignature,
                    CertificateKeyUsage.KeyEncipherment,
                    CertificateKeyUsage.KeyAgreement,
                    CertificateKeyUsage.KeyCertSign
                },
                ValidityInMonths = 12,
                LifetimeActions  =
                {
                    new LifetimeAction(CertificatePolicyAction.AutoRenew)
                    {
                        DaysBeforeExpiry = 90,
                    }
                }
            };
            #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy

            #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy
            //@@CertificatePolicy policy = CertificatePolicy.Default;
            /*@@*/ policy = CertificatePolicy.Default;
            #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy

            {
                #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate
                // Start certificate creation.
                // Depending on the policy and your business process, this could even take days for manual signing.
                CertificateOperation createOperation = await client.StartCreateCertificateAsync("certificate-name", policy);

                KeyVaultCertificateWithPolicy certificate = await createOperation.WaitForCompletionAsync(TimeSpan.FromSeconds(20), CancellationToken.None);

                // If you need to restart the application you can recreate the operation and continue awaiting.
                createOperation = new CertificateOperation(client, "certificate-name");
                certificate     = await createOperation.WaitForCompletionAsync(TimeSpan.FromSeconds(20), CancellationToken.None);

                #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate
            }

            {
                #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate
                byte[] cer = File.ReadAllBytes("certificate.pfx");
                ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions("certificate-name", cer)
                {
                    Policy = policy
                };

                KeyVaultCertificateWithPolicy certificate = await client.ImportCertificateAsync(importCertificateOptions);

                #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate
            }

            {
                #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates
                // List all certificates asynchronously.
                await foreach (CertificateProperties item in client.GetPropertiesOfCertificatesAsync())
                {
                    KeyVaultCertificateWithPolicy certificate = await client.GetCertificateAsync(item.Name);
                }

                // List all certificates synchronously.
                foreach (CertificateProperties item in client.GetPropertiesOfCertificates())
                {
                    KeyVaultCertificateWithPolicy certificate = client.GetCertificate(item.Name);
                }
                #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates
            }

            {
                #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate
                // Delete the certificate.
                DeleteCertificateOperation deleteOperation = await client.StartDeleteCertificateAsync("certificate-name");

                // Purge or recover the deleted certificate if soft delete is enabled.
                if (deleteOperation.Value.RecoveryId != null)
                {
                    // Deleting a certificate does not happen immediately. Wait for the certificate to be deleted.
                    DeletedCertificate deletedCertificate = await deleteOperation.WaitForCompletionAsync();

                    // Purge the deleted certificate.
                    await client.PurgeDeletedCertificateAsync(deletedCertificate.Name);

                    // You can also recover the deleted certificate using StartRecoverDeletedCertificateAsync,
                    // which returns RecoverDeletedCertificateOperation you can await like DeleteCertificateOperation above.
                }
                #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate
            }
        }