简体   繁体   中英

Python Azure Function - MSI Authentication with Key Vault

I am trying to setup a Python Azure Function that will use a Managed Identity to retrieve secrets from key vault. I have given my Function App's Managed Identity permission to access and retrieve secrets from the Key Vault. I have configured my Python script as such according to the Microsoft documents seen here:

https://docs.microsoft.com/en-us/python/api/overview/azure/key-vault?view=azure-python

Instead of using Default Credential, I am trying to utilize the MSI Authentication, as documented here:

https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate#mgmt-auth-msi

If I use the example that is provided in the link for MSI Authentication, it works. But when I use the Key Vault method I receive the following error:

MSIAuthentication' object has no attribute 'get_token'

My code for this looks as follows

    if name:
        # Create MSI Authentication
        credentials = MSIAuthentication()

        try:
            secret_client = SecretClient(vault_url="https://myvault.vault.azure.net", credential=credentials)

            secret = secret_client.get_secret("mySecret") 

            return func.HttpResponse(f"My super secret is: {secret.value}!")

        except Exception as e:
            err = "type error: " + str(e)
            return func.HttpResponse(f"{err}")

Any suggestions on how I can get this method to work.

TIA

( I know I can utilize Application settings to setup a link to Key Vault and reference that variable in my Python script. The issue with this method is that key vault key is that when keys get rotated it becomes necessary to restart the function app )

You need to change the MSIAuthentication into ManagedIdentityCredential . Then it will work fine. The example code here:

from azure.identity import ManagedIdentityCredential
from azure.keyvault.secrets import SecretClient

credentials = ManagedIdentityCredential()

secret_client = SecretClient(vault_url="https://myKeyvault.vault.azure.net", credential=credentials)
secret = secret_client.get_secret("mysecret")
print(secret.value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM