Azure Key Vault and Certificate - .NET Framework ClientCertificateCredential access to Secrets

1k views Asked by At

I have generated .pfx, .pvk and .cer certification files.

In Azure:

  • I created a new Vault, let's call it MyVault
  • In MyVault, I created a Secret called SubscriptionKey
  • MyVault has a Certificates section to which I've uploaded MyCertificate.cer file.

Confusingly enough, Azure also has a "Azure Active Directory" section where I can also upload Certificates. This is what I understood from researching, to be the place where to upload the certificate, and get the associated clientId and tenantId needed for the ClientCertificateCredential constructor.

Goal: Retrieve the secret value from MyVault using a Certificate and the code:

public static string GetSecretFromAzureKeyVault(string secretName)
        {
            string vaultUrl = "https://MyVault.vault.azure.net/";
            string cerPath = "C:\\Personal\\MyCertificate.cer";

            ClientCertificateCredential credential = new(
                    "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
                    "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
                    cerPath
                );

            SecretClient client = new(new Uri(vaultUrl), credential);
            KeyVaultSecret secret = client.GetSecret(secretName);

            return secret.Value;
        }

When running the code I'm still getting null for the line:

KeyVaultSecret secret = client.GetSecret(secretName);

Any suggestions on what I've done wrong in this flow or regarding the resources?

EDIT:

Error screenshot: image_A

1

There are 1 answers

16
Rajesh  Mopati On

I have followed the below steps and got the secret value

  1. Create an app from AAD and register the app using APP registrations.

enter image description here

  1. Create a keyVault and secret. And use the secret name in the code.

enter image description here

  1. Use the ClientId and TenantId from the App registrations and use it in the code.

enter image description here

  1. Download the .pfx format file and use the certificate in the code.

enter image description here

  1. Use .pfx downloaded path in code

enter image description here

public static string GetSecretFromAzureKeyVault(string secretName)
            {
                string vaultUrl = "https://keyvault.vault.azure.net/";
                string cerPath = "C:\\Tools\\keyvault-keycertificate-20230109.pfx";
    
                ClientCertificateCredential credential = 
                    new ClientCertificateCredential("TenantId", "ClientId", cerPath);
    
                SecretClient client = new SecretClient(new Uri(vaultUrl), credential);
                KeyVaultSecret secret = client.GetSecret(secretName);
    
                return secret.Value;
            }

You can find the secret value in the below highlighted screen.

enter image description here