Using Azure.Security.KeyVault to retrieve certificate (PFXcontent) via SecretId / SecretIdentifier instead of Microsoft.Azure.KeyVault

Viewed 1466

Just wondering how you would achieve the same using the new Azure.Security.KeyVault libraries:

  1. Azure.Security.KeyVault.Certificates

https://docs.microsoft.com/en-us/dotnet/api/overview/azure/security.keyvault.certificates-readme?view=azure-dotnet

  1. Azure.Security.KeyVault.Secrets

https://docs.microsoft.com/en-us/dotnet/api/overview/azure/security.keyvault.secrets-readme?view=azure-dotnet#retrieve-a-secret

Particularly with regards to getting the PFX content from the certificate SecretId. The new libraries don't seem to offer a way to get the Secret by SecretId or SecretIdentifier, only by name.

With the aim of matching what would have previously been done like this:

var azureServiceTokenProvider = new AzureServiceTokenProvider();

var keyVaultClient = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

CertificateBundle certificateBundle = await keyVaultClient.GetCertificateAsync(certificateIdentifier);

SecretBundle certificateWithPrivateKey = await keyVaultClient.GetSecretAsync(certificateBundle.SecretIdentifier.Identifier);

byte[] certificateWithPrivateKeyDecoded = Convert.FromBase64String(certificateWithPrivateKey.Value);

var certificate = new X509Certificate2(certificateWithPrivateKeyDecoded, (string)null);

return certificate;
1 Answers

Yes, the method does not offer a way to get the Secret by SecretIdentifier, but it has a parameter version, see SecretClient.GetSecret(String, String, CancellationToken).

In your case, if you have the certificateIdentifier, the secret name and version are included, they are the same as the certificate, just pass them to the method.

enter image description here

var client = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());
KeyVaultSecret secret = client.GetSecret("secret-name","secret-version");
Related