I want to add Azure Key Vault to my C# app but I'd like to run the code locally. Is there a possible way? A lot of documentation says that AKV only works on Azure env but
So here you can see my Key Vault access policies. RBAC is checked.
The Managed Identity has a role assigned to the Key Vault as Key Vault Administrator (for testing purpose)
My Managed Identity is assigned as User Assigned Managed Identity in my App Service on Identity tab.
My Program.cs looks like this:
var userAssignedClientId = "Some guid";
if (!string.IsNullOrEmpty(MyVaultUri))
{
builder.Configuration.AddAzureKeyVault(
new Uri(MyVaultUri),
new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedClientId }));
}
I have declared the env variables AZURE_TENANT_ID
, AZURE_CLIENT_ID
, AZURE_CLIENT_SECRET
and the nugget packages Azure.Identity v1.4.0, Azure.Security.KeyVault.Secrets v4.3.0 installed.
And this is what I'm getting as error in localhost: Azure.RequestFailedException: 'Caller is not authorized to perform action on resource.
CodePudding user response:
When wanting to connect to online resources there are a few options available that Microsoft supplies. One of them is the InteractiveBrowserCredential which prompts you with the question of entering your credentials.
The other is the DefaultAzureCredential which on first looks is quite deceiving because what is the default? According to the documentation it tries six different types of authorization before returning an error when authorizing fails. Note that if one of the types is disabled, it won't be used.
If you are logged in with the same credentials from the portal.azure.com in Visual Studio then the authentication will happen seamlessly.
Also note that when you want to use environment variables on your localhost. Instead defining those on the machine, it's a best practice to use a settings file which holds the variables. Don't forget to add that settings file to the gitignore file. You don't want those secrets to be published to a public repo.
CodePudding user response:
As long as you are only using keys and secrets, and it is fine that the keys are not the same as in the environment you tried to connect to, you could possibly get away with using a test double, such as Lowkey Vault.
You can find the project here: https://github.com/nagyesta/lowkey-vault
Also, there is a .Net POC here: https://github.com/nagyesta/lowkey-vault-example-dotnet