I am unsure how to authenticate against an Azure keyvault from my local machine. While I understand I would probably never want to do that in a production scenario, I do want to do it for testing its use prior to production.
Is that possible?
While I did see several options, I failed to use DefaultAzureCredential and also CertificateCredential, ClientSecretCredential which I tried later, each with his own error, which I didn't completely understand.
The default one told me that: azure.core.exceptions.HttpResponseError: (Forbidden) The user, group or application 'appid=a79ae17f-90f7-4341-a2f7-b4ae4abad7d2;oid=cb8a8745-1567-4cd7-b8a0-5cecd6afe6c6;iss=https://sts.windows.net/98d1d263-cc4b-4d75-96a6-daf642242d3b/' does not have secrets get permission on key vault 'AnotherKV2;location=eastus'
azure.core.exceptions.HttpResponseError: (Forbidden) The user, group or application 'appid={MYAPPID};oid={SomeOID};iss=https://sts.windows.net/98d1d263-cc4b-4d75-96a6-daf642242d3b/' does not have secrets get permission on key vault '{MyKVName};location=eastus'. For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125287
Which is weird for two reasons:
Firstly, while I did define a SP with {MYAPPID} in my subscription, I don't recall ever using it in my local machine, so how did my local app have the same APPID as (I assumed was automatically generated) the one I got when I created the service principals with the command: az ad sp create-for-rbac --name "MyApp"
Secondly, looking at the access policy of my keyvault, it appears that {MYAPPID} is given permission to do right about everything
Am I missing something? Should it be done some other way? (Or not at all?)
When you run your code locally, DefaultAzureCredential
automatically uses the service principal described by the environment variables named AZURE_TENANT_ID
, AZURE_CLIENT_ID
, and AZURE_CLIENT_SECRET
.
So to use it, please Set environmental variables
in the advanced setting locally first, just use the values of the AD App created by az ad sp create-for-rbac
.
To access the keyvault secret, you need to add the service principal related to the AD App to the Access policies
of your keyvault with correct secret permission Get, List
.
Note: Make sure the service principal is in the same Azure AD tenant with your keyvault, when you add it, please search for the APP ID/Client ID
directly, because two different apps can have the same name.
Then use the code below, it works for me.
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
client = SecretClient(vault_url="https://keyvaultname.vault.azure.net/", credential=credential)
retrieved_secret = client.get_secret("sec789")
print(retrieved_secret.value)
For more details, see https://learn.microsoft.com/en-us/azure/key-vault/secrets/quick-create-python