Problem reading environmental variables to authenticate with Azure

145 views Asked by At

I have a dotnet 6.0 worker service running on Windows Server 2022 Standard.

In order to authenticate with Azure I am using DefaultAzureCredential and have set Environmental variables against the appropriate registry key for the tenant, client, and client secret as per https://learn.microsoft.com/en-us/dotnet/api/azure.identity.environmentcredential?view=azure-dotnet.

When connecting to Azure I get the error: "EnvironmentCredential authentication unavailable. Environment variables are not fully configured."

Upon further debugging I can see that the values for AZURE_CLIENT_ID and AZURE_CLIENT_SECRET are correctly set and available to the service.

The problem is that AZURE_TENANT_ID is not set. It can be seen in regedit, and the value is correct.

I added a log of

var tid = Environment.GetEnvironmentVariable("AZURE_TENANT_ID") ?? "*missing*"; 

this returned *missing*, doing the same for the other variables returns the expected value.

I am using the exact same code in a net48 app and this works as expected. The environment variables are set using PowerShell via Octopus deploy in both cases.

I have done the usual checks for things like typos or smart quotes. I have also added a leading dummy key in case it was a problem with the 1st value.

For now I can work around this with Environment.SetEnvironmentVariable("AZURE_TENANT_ID","foo"); but I would like this to work as intended with out the work around.

1

There are 1 answers

1
Tore Nestenius On

In the source for the EnvironmentCredential (inside DefaultAzureCredential), you see that it does need all three (tenantId, ClientID, and Secret)

Otherwise it skips the environment variables all together and move on to the next tokenCredential to try.

if (!string.IsNullOrEmpty(tenantId) && !string.IsNullOrEmpty(clientId))
{
    if (!string.IsNullOrEmpty(clientSecret))
    {
        Credential = new ClientSecretCredential(tenantId, clientId, clientSecret, envCredOptions, _pipeline, envCredOptions.MsalConfidentialClient);
    }
    else if (!string.IsNullOrEmpty(clientCertificatePath))
    {
        ClientCertificateCredentialOptions clientCertificateCredentialOptions = envCredOptions.Clone<ClientCertificateCredentialOptions>();

        clientCertificateCredentialOptions.SendCertificateChain = sendCertificateChain;

        Credential = new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificatePassword, clientCertificateCredentialOptions, _pipeline, envCredOptions.MsalConfidentialClient);
    }
    else if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
    {
        Credential = new UsernamePasswordCredential(username, password, tenantId, clientId, envCredOptions, _pipeline, envCredOptions.MsalPublicClient);
    }
}
}