authenticationconsole-application.net-6.0azure-keyvault

How to retrieve secret from Azure Key Vault from console application


I want to execute a console application on a remote machine with a service account that retrieves a secret from Azure Key Vault, so I do not have to put this secret in the source code or any kind of config file.
I was able to create the secret and permit the user read access.
I fail to authenticate to Key Vault in code.

Here are the two lines of code:

var client = new SecretClient(new Uri($"https://kv-xxx.vault.azure.net"), new DefaultAzureCredential());
var secret = client.GetSecret("xxx-api-key");

I get a list of exceptions starting with Azure.Identity.CredentialUnavailableException.
All attempts from DefaultAzureCredential fail.

I cannot use the recommended 'managed identity for applications'. The application runs on a server in the context of a service account.
I was under the impression all the authentication details would be passed along fully transparently, as this is the case for other resources.
I verified via Azure portal that the account has proper permissions to read the secret.

I feel the stack trace and additional arbitrary information on hand do not contribute to finding a solution.


Solution

  • To retrieve the secret value, create an Azure AD/Microsoft Entra ID application:

    enter image description here

    To get the secret value, the application must have Key Vault Secrets User role :

    Go to your Key vault -> Access control (IAM) -> Add -> Add role assignment -> Select Key Vault Secrets User -> Select members -> Select your application -> Review + assign

    enter image description here

    Now use the below code and the secret value will be retrieved successfully:

    using Azure.Identity;
    using Azure.Security.KeyVault.Secrets;
    
    var clientId = "ClientIDofApp";
    var clientSecret = "ClientSecretofApp";
    var vaultUri = new Uri("https://rukkvs.vault.azure.net/");
    var tenantId = "TenantID";
    var secretname = "testsecret";
    
    var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    var client = new SecretClient(vaultUri, credential);
    var secret = client.GetSecret(secretname);
    
    Console.WriteLine($"secret value for the secret {secretname} is {secret.Value.Value}");
    

    enter image description here