使用Azure Python SDK,我想使用KeyVaultClient
方法返回一个get_client_from_auth_file
,以便从KeyVault中获取机密,而无需通过KeyVaultManagementClient
。
根据documentation,似乎可以从任何SDK客户端类创建客户端。
我能够做到这一点:
from azure.common.client_factory import get_client_from_auth_file
from azure.mgmt.keyvault import KeyVaultManagementClient
_kv_mgmt_client = get_client_from_auth_file(KeyVaultManagementClient)
但不是这样:
from azure.common.client_factory import get_client_from_auth_file
from azure.keyvault import KeyVaultClient
_kv_client = get_client_from_auth_file(KeyVaultClient)
这是错误消息:TypeError: __init__() got an unexpected keyword argument 'base_url'
经审查,get_client_from_auth_file
返回多个结果,包括base_url
,因此以下帮助函数可解决TypeError
。
class KeyVaultClientHelper:
def __init__(self, credentials, **kwargs):
self._credentials = credentials
KeyVaultClient成功,直到尝试获取密码并返回Unauthorized
。
helper = get_client_from_auth_file(KeyVaultClientHelper)
client = KeyVaultClient(helper._credentials)
print(client.get_secret("http://my-vault-url...", "MY-KEY", '').value))
但是,我成功使用带有相同身份验证文件的ServicePrincipalCredential
来获取机密。
答案 0 :(得分:1)
这是azure常见的错误,已在1.1.22中修复: https://pypi.org/project/azure-common/1.1.22/
谢谢!
答案 1 :(得分:-1)
克里斯汀,
您可以尝试以下类似方法,它具有用于获取Keyvault客户端的有效示例
import adal
from azure.keyvault import KeyVaultClient, KeyVaultAuthentication
from azure.common.credentials import ServicePrincipalCredentials
from msrestazure.azure_active_directory import AADTokenCredentials
client_id = '<client_id>'
client_secret = '<client_secret>'
tenant = '<tenant>'
vault_address = '<vault_address>'
secret_name = '<secret_name>'
resource_uri = 'https://vault.azure.net'
def auth_with_adal(server, resource, scope):
authority_host_uri = 'https://login.windows.net'
authority_uri = authority_host_uri + '/' + tenant
context = adal.AuthenticationContext(authority_uri, api_version=None)
mgmt_token = context.acquire_token_with_client_credentials(resource_uri, client_id, client_secret)
credentials = AADTokenCredentials(mgmt_token, client_id)
token = credentials.token
return token['token_type'], token['access_token']
def auth_with_spc(server, resource, scope):
credentials = ServicePrincipalCredentials(
client_id = client_id,
secret = client_secret,
tenant = tenant,
resource = resource_uri
)
token = credentials.token
return token['token_type'], token['access_token']
try:
client = KeyVaultClient(KeyVaultAuthentication(auth_with_adal))
secret_bundle = client.get_secret(vault_address, secret_name, '')
print('1) I got the secret using AADTokenCredentials!')
except Exception as e:
print('1) Failed to get a secret!')
print(e)
try:
client = KeyVaultClient(KeyVaultAuthentication(auth_with_spc))
secret_bundle = client.get_secret(vault_address, secret_name, '')
print('2) I got the secret using ServicePrincipalCredentials!')
except Exception as e:
print('2) Failed to get a secret!')
print(e)
您可以使用以下功能来实现它。
client = KeyVaultClient(KeyVaultAuthentication(auth_with_spc))
希望有帮助。