Beispiel #1
0
        public async Task <string[]> GetCertificateThumbprintsAsync(CancellationToken cancellationToken)
        {
            var thumbprints = new List <string>();

            await foreach (var cert in _certificateClient.GetPropertiesOfCertificateVersionsAsync(_certificateName, cancellationToken))
            {
                thumbprints.Add(ThumbprintHelper.Convert(cert.X509Thumbprint));
            }
            return(thumbprints.ToArray());
        }
Beispiel #2
0
    /// <inheritdoc/>
    public async Task <string> GetCertificateAsync(string vaultUri, string secretId)
    {
        CertificateClient certificateClient = new CertificateClient(new Uri(vaultUri), new DefaultAzureCredential());
        AsyncPageable <CertificateProperties> certificatePropertiesPage = certificateClient.GetPropertiesOfCertificateVersionsAsync(secretId);

        await foreach (CertificateProperties certificateProperties in certificatePropertiesPage)
        {
            if (certificateProperties.Enabled == true &&
                (certificateProperties.ExpiresOn == null || certificateProperties.ExpiresOn >= DateTime.UtcNow))
            {
                SecretClient secretClient = new SecretClient(new Uri(vaultUri), new DefaultAzureCredential());

                KeyVaultSecret secret = await secretClient.GetSecretAsync(certificateProperties.Name, certificateProperties.Version);

                return(secret.Value);
            }
        }

        return(null);
    }
        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));
        }
Beispiel #4
0
        private async Task <TrackKeyExternal> LoadTrackKeyExternalFromKeyVaultAsync(Track track)
        {
            var now = DateTimeOffset.UtcNow;
            var certificateClient = new CertificateClient(new Uri(settings.KeyVault.EndpointUri), tokenCredential);

            var externalKeys        = new List <(string Id, DateTimeOffset?NotBefore)>();
            var certificateVersions = certificateClient.GetPropertiesOfCertificateVersionsAsync(track.Key.ExternalName);

            await foreach (var certificateVersion in certificateVersions)
            {
                if (certificateVersion.Enabled == true && certificateVersion.ExpiresOn >= now)
                {
                    externalKeys.Add((certificateVersion.Version, certificateVersion.NotBefore));
                }
            }

            if (externalKeys.Count <= 0)
            {
                throw new Exception($"Track key external certificate '{track.Key.ExternalName}' do not exist in Key Vault.");
            }

            var trackKeyExternal = new TrackKeyExternal();

            if (externalKeys.Count == 1)
            {
                trackKeyExternal.Keys = new List <TrackKeyExternalItem> {
                    new TrackKeyExternalItem {
                        ExternalId = externalKeys.First().Id
                    }
                };
            }
            else
            {
                var topTwoExternalKeys = externalKeys.OrderByDescending(e => e.NotBefore).Take(2);
                var firstExternalKey   = topTwoExternalKeys.First();
                if (firstExternalKey.NotBefore <= now.AddDays(-track.KeyExternalPrimaryAfterDays))
                {
                    trackKeyExternal.Keys = new List <TrackKeyExternalItem> {
                        new TrackKeyExternalItem {
                            ExternalId = firstExternalKey.Id
                        }, new TrackKeyExternalItem {
                            ExternalId = topTwoExternalKeys.Last().Id
                        }
                    };
                }
                else
                {
                    trackKeyExternal.Keys = new List <TrackKeyExternalItem> {
                        new TrackKeyExternalItem {
                            ExternalId = topTwoExternalKeys.Last().Id
                        }, new TrackKeyExternalItem {
                            ExternalId = firstExternalKey.Id
                        }
                    };
                }
            }

            foreach (var keyItem in trackKeyExternal.Keys)
            {
                var certificateWithPolicy = certificateClient.GetCertificateVersion(track.Key.ExternalName, keyItem.ExternalId);
                var certificateRawValue   = certificateWithPolicy?.Value?.Cer;
                if (certificateRawValue == null)
                {
                    throw new Exception($"Track key external certificate '{track.Key.ExternalName}' version '{keyItem.ExternalId}' from Key Vault is null.");
                }
                keyItem.Key = await new X509Certificate2(certificateRawValue).ToFTJsonWebKeyAsync();
            }
            return(trackKeyExternal);
        }