DefaultAzureCredential doesn't authenticate successfully (even when logged in via CLI
How to use User-Managed Identity from Azure Cloud Function (python) in making a request to Azure KeyVault? - Stack Overflow
Use DefaultAzureCredential() with service principal and federated identity credentials
Uncaught Exception in DefaultAzureCredential
When you use a user-assigned identity, you need to specify the client_id of the MSI in ManagedIdentityCredential().
credential = ManagedIdentityCredential(client_id="xxxxxxxx")
To get the client_id, navigate to your function app -> Identity -> User assigned -> click your user-assigned identity -> copy the client_id.

Here is how you would use Managed Identity in python:
from msrestazure.azure_active_directory import MSIAuthentication
creds = MSIAuthentication()
client = SecretClient(vault_url=MyVaultUrl, credentials=creds)
For this to work however, you have to have the identity assigned to your azure function as part of the deployment. If you are using terraform, there is a provider which you can use and it accepts an identity {} block where you can specify type="UserAssigned" and identity_ids = ["id1", "id2",...]
When using Azure Identity client library for Python, DefaultAzureCredential attempts to authenticate via the following mechanisms in this order, stopping when one succeeds:

You could set Environment Variables to fix it.

from azure.identity import DefaultAzureCredential
credential=DefaultAzureCredential()
Or set the properties in config and use ClientSecretCredential to create credential.
from azure.identity import ClientSecretCredential
subscription_id = creds_obj["AZURE_SUBSCRIPTION_ID"]
tenant_id = creds_obj["AZURE_TENANT_ID"]
client_id = creds_obj["AZURE_CLIENT_ID"]
client_secret = creds_obj["AZURE_CLIENT_SECRET"]
credential = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
I was having somewhat similar trouble following this Azure key vault tutorial which brought me here.
The solution I found was overriding the default values in the DefaultAzureCredential() constructor.
https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.defaultazurecredential?view=azure-python
For reasons people far smarter than me will be able to explain I found that even though I had credentials from the azure cli it was not using those and instead looking for environment_credentials, which I did not have. So it threw an exception.
Once I set the exclude_environment_credential argument to True it then looked instead for the managed_identity_credentials, again which I did not have.
Eventually when I force excluded all credentials other than those from the cli it worked ok for me
I hope this helps someone. Those with more experience please feel free to edit as you see fit



