Reputation: 693
In my current Net Core 3.1 WPF project I want the user to be able to connect to a Azure Key Vault. I have a key vault set up with some access policies set up or users.
In the documentation I read a lot about setting up connection to a key vault with environment variables using SecretClient(new Uri(_keyVaultUrl), new DefaultAzureCredential());
. What I don't understand is how environment variables can be of any use here, because they are limited to a single machine that has set them.
The above code returns a Null object error in my code:
Azure.Identity.CredentialUnavailableException: 'DefaultAzureCredential failed to retrieve a token from the included credentials.
- EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
- ManagedIdentityCredential authentication unavailable. The requested identity has not been assigned to this resource.
Status: 400 (Bad Request)
Is there a direct way where I can use a client-secret, app-id and then connect and authenticate with the azure key vault, using the Azure Identity library?
Upvotes: 0
Views: 1250
Reputation: 16438
Firstly, setting environment variables is for Azure.Identity
to use to create the DefaultAzureCredential()
. So you need to set them.
If your app is hosted on Azure, you could easily use the managed identity with DefaultAzureCredential
to access Azure KeyVault by following this sample and this document.
Remember to Set access policy (it's environment variables in Azure) in the step 1 in the first link above, which grants your service principal / managed identity access to the Key Vault.
But as you said your app is an WPF, which is likely to run locally (corresponds to hosted on Azure). In this case, you don't have a managed identity, but you still can create a service principal to access your Azure KeyVault.
You can refer to this document: Azure Key Vault secret client library for .NET - Version 4.2.0-beta.5.
After you create the service principal, the most important thing is the same as what I mentioned previously: Set access policy (you will see the environment variables in this step). You can set it in Powershell like this:
az keyvault set-policy --name <your-key-vault-name> --spn $Env:AZURE_CLIENT_ID --secret-permissions backup delete get list set
And then create SecretClient to access KeyVault:
// Create a new secret client using the default credential from Azure.Identity using environment variables previously set,
// including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
var client = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());
// Create a new secret using the secret client.
KeyVaultSecret secret = client.SetSecret("secret-name", "secret-value");
// Retrieve a secret using the secret client.
secret = client.GetSecret("secret-name");
Upvotes: 3