I dont have a great understanding of Key Vault & certificates and struggling with an issue. I am making use of a PFX file to generate a JWT token to call an external webservice. Its working all right. Now I need to store the PFX in Key Vault and do the same.
I am uploading the cert using Az DevOps & Az Cli command
az keyvault certificate import --file $(filename.secureFilePath) --name pfx-cert-name --vault-name "keyvault-name" --password "password"
Now when I try to use the PFX in my .net core. I am using CertificateClient class & GetCertificateAsync methods to fetch the byte array of a PFX file.
var client = new CertificateClient(new Uri(kvUri), new DefaultAzureCredential()); var cert = await client.GetCertificateAsync(certName);
certInBytes = cert.Value.Cer;
The code fails. After doing online reading, I understand its because Get Certificate fetches the public details of the PFX file. Hence I started doing some reading online and doing import and download using Az Cli command on powershell.
I tried another technique to download original form of PFX using the below command:
az keyvault secret download --file inputCert.pfx --vault-name keyvault-name --encoding base64 --name pfx-cert-name
The command gives me another pfx but its still not the original form of PFX. When I try to use this cert to get JWT token, I get an error for invalid password.
I have two alternates, but I don’t want to use either as they are not clean solutions:
- Either store a byte array of PFX as a secret in key vault
- Store base 64 encoded version of byte array of pfx for extra security.
2
Answers
There are 2 ways to solve this problem. One with the help of DefaultCredentials class while the other solution being with the help of a SPN using class ClientSecretCredentials.
I have written a detailed article on both the solution. Since the original problem was in regards to DefaultCredentials, I wrote about it first
https://blog.devgenius.io/fetch-pfx-cert-from-key-vault-using-defaultcredentials-3795bd23d294?sk=be8a6fea080ff19056a0b90fc9532cd7
https://blog.devgenius.io/fetch-pfx-cert-from-key-vault-using-clientsecretcredentials-c0e80b129b37?sk=63c93f776bde72f49ef12263838e8d82
To get the certificate with its private key, then you need to download it as a secret, not as a certificate. Yes, it does sounds weird, by that is how you do it.
This is the code I use to download a certificate with private key from AKV:
The code above depends on these NuGet packages: