Python azure.identity中AADCredentials的替代

问题描述

我以前使用过Azure Python SDK模块AADCredentials对来自azure-mgmt-resource的客户端(例如SubscriptionClient)进行身份验证。随着推出天蓝色身份,我发现无法将AADCredentials与天蓝色身份客户端(例如SecretClient)一起使用来访问KeyVault。 简而言之,我试图找到一种使用外部生成的身份验证令牌作为服务主体的方法,以创建SecretClient可使用的凭据,而无需重写AADCredentials以添加get_token方法。 例如

from azure.keyvault.secrets import SecretClient
from msrestazure.azure_active_directory import AADTokenCredentials

token={'tokenType':'Bearer','accessToken':'BLAH'}
client_id='123'
cred=AADTokenCredentials(cred,client_id=client_id)
secret_client=SecretClient(vault_url=vault_url,credential=creds)

#Errors with 'AADTokenCredentials has no attribute 'get_token'
retrieved_secret=secret_client.get_secret('secretname')

我正在尝试这样做,以使Python无法访问服务主体证书,因此无法将其与密码一起复制到其他地方。

任何想法都会受到赞赏

解决方法

azure-identity不包括等效的凭证,但是有一个示例演示如何编写执行相同操作的自定义凭证(来自custom credentials sample):

from azure.core.credentials import AccessToken

class StaticTokenCredential(object):
    """Authenticates with a previously acquired access token

    Note that an access token is valid only for certain resources and eventually expires.
    This credential is therefore quite limited. An application using it must ensure
    the token is valid and contains all claims required by any service client given an
    instance of this credential.
    """
    def __init__(self,access_token):
        # type: (Union[str,AccessToken]) -> None
        if isinstance(access_token,AccessToken):
            self._token = access_token
        else:
            # Setting expires_on in the past causes Azure SDK clients to call
            # get_token every time they need a token. You could adapt this class
            # to use the token's actual expires_on value,if you know it.
            self._token = AccessToken(token=access_token,expires_on=0)

    def get_token(self,*scopes,**kwargs):
        # type: (*str,**Any) -> AccessToken
        return self._token

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...