Search code examples
azure-sdk-python

Can't authenticate to KeyVault - No credential in this chain provided a token


I'm trying to authenticate to a Key Vault using DefaultAzureCredential object with username/password authentication, but I'm getting this error:

[06/10/2020 13:57:37] Exception: ClientAuthenticationError: 
[06/10/2020 13:57:37] No credential in this chain provided a token.
[06/10/2020 13:57:37] Attempted credentials:
[06/10/2020 13:57:37]   EnvironmentCredential: Authentication failed: Unable to find wstrust endpoint from MEX. This typically happens when attempting MSA accounts. More details available here. https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Username-Password-Authentication
[06/10/2020 13:57:37] 
[06/10/2020 13:57:37] Please visit the documentation at
[06/10/2020 13:57:37] https://aka.ms/python-sdk-identity#defaultazurecredential
[06/10/2020 13:57:37] to learn what options DefaultAzureCredential supports

I can confirm that the required environment variables are being loaded from local.settings.json:

  • AZURE_CLIENT_ID

  • AZURE_USERNAME

  • AZURE_PASSWORD

Relevant code:

def encrypt(text):
    uri = os.environ['KEYVAULT_URI']
    credential = DefaultAzureCredential()
    key_client = KeyClient(vault_url=uri, credential=credential)

    key = key_client.get_key("managed-key")
    crypto_client = CryptographyClient(key, credential=credential)
    plaintext = text.encode()

    return crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep, plaintext)

local.settings.json looks like this:

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "{AzureWebJobsStorage}",
    "KEYVAULT_URI": "<keyvault_uri>",
    "AZURE_CLIENT_ID": "<client_id>",
    "AZURE_USERNAME": "<email>",
    "AZURE_PASSWORD": "<password>"
  }
}

Solution

  • After writing the question I read the docs and found out the reason. Also the error trace is clear:

    This typically happens when attempting MSA accounts.
    

    Can't use a personal Microsoft account for this. Only work and school accounts would do.

    From Username Password Authentication:

    By design and policy, the username/password authentication works only for Work and school accounts, but not for Microsoft Accounts (MSA).

    I switched to service principal with secret and it solved my problem.

    Details on options available at EnvironmentCredential.

    "AZURE_TENANT_ID": "",
    "AZURE_CLIENT_ID": "",
    "AZURE_CLIENT_SECRET": ""