I have the following code loading Azure Key Vault secrets into the configuration of a worker process on startup. The process is configured in Azure and associated to a certificate which is also installed on the machine where the process runs.
This code works most of the time, which is the infuriating problem. A few times a day, on the call to Build()
, connecting to the key vault fails with a message of Unauthorized
, and takes down the entire application. Then, it inexplicably starts working again on restart. I believe this may have something to do with Azure Active Directory token expiration, but I don't know what to do about it, as the code below is almost verbatim from the documentation. This process is long-running and unattended, so random failures are not acceptable.
I have tried adding logic to wait a few seconds on failure and retry, but it didn't seem to help. Using the certificate method of authentication is a hard requirement from the security team.
using (var certStore = new X509Store(certLocation, StoreLocation.CurrentUser))
{
try
{
certStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var certSearch = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
// We expect a single result
if (certSearch.Count == 1)
{
var result = certSearch.OfType<X509Certificate2>().Single();
//Add the key vault as a config provider
builder.AddAzureKeyVault($"https://{config[keyVaultName]}.vault.azure.net/",
config[applicationId],
result);
//This will fail if Keyvault is not configured properly
builder.Build();
}
}
finally
{
certStore.Close();
}
}