azure-active-directorydefaultazurecredential

How to use more than one secret value with Default Azure Credential


I am using Default Azure Credential to get a token for calling API's in a function app.

I can retrieve token running locally and I can also get one when the function app is running in Azure by setting the AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_TENANT_ID in the app settings of the function app.

Now however, I want to call another API from my function app, but this is secured with a different app registration in Entra ID. As such there is a different Client ID and Secret value for that.

The problem is there only appears to be the 1 app setting value that the Default Credential is looking for (AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_TENANT_ID).

Is there any way to tell the Default Azure Credential which app settings to look at when running in Azure?

If It helps here is the code that is successfully getting the token when running locally and in Azure

public async Task<string> GetToken()
{
    var scope = $"{_clientId}/.default";

    DefaultAzureCredential credential = new DefaultAzureCredential();

    var accessToken = credential.GetToken(new TokenRequestContext(scopes: new[] { scope }));

    return accessToken.Token;
}

Solution

  • You should typically assign a Managed Identity (either system generated or user provided) to your service and not using App registrations inside Azure. App registrations are mainly for clients outside Azure (as of my understanding). I understand what you are trying to do, but I think you are on the wrong track here .

    You can't customize DefaultAzureCredential that much, except exclusing certain credential sources.

    The alternative is to replace DefaultAzureCredential with your own credential using:

    Credential = new ClientSecretCredential(tenantId, clientId, clientSecret...);