Python 3.x 重用从DeviceCodeCredential获取的令牌
我正在使用以下代码获取azure blob服务的令牌:Python 3.x 重用从DeviceCodeCredential获取的令牌,python-3.x,azure-active-directory,azure-blob-storage,Python 3.x,Azure Active Directory,Azure Blob Storage,我正在使用以下代码获取azure blob服务的令牌: from azure.storage.blob import BlobServiceClient from azure.identity import InteractiveBrowserCredential, DeviceCodeCredential, ClientSecretCredential credential = DeviceCodeCredential(authority="login.microsoftonline.com
from azure.storage.blob import BlobServiceClient from azure.identity import InteractiveBrowserCredential, DeviceCodeCredential, ClientSecretCredential
credential = DeviceCodeCredential(authority="login.microsoftonline.com", tenant_id="***", client_id="***")
blobber = BlobServiceClient(account_url="https://***.blob.core.windows.net", credential=credential)
blobs = blobber.list_containers()
for b in blobs:
print(b)
它工作得很好
但是,在特定时间段内,用户可能需要多次调用blob服务。关键的一点是,该进程可能会多次关闭和重新打开
让用户每次重新启动交互令牌获取过程都会非常烦人。我希望持久化令牌并在以后的流中重用它,直到它过期(假设持久化是安全的)
我应该使用什么类型的凭证?ClientSecretCredential不工作。或者,可能有一种令牌缓存机制我不知道
编辑:
我转寄了一封信。它也有一个有效的答案。
谢谢Jim Xu。根据我的研究,DeviceCodeCredential不会缓存令牌——每个
获取令牌(*scopes,**kwargs)
调用都会启动一个新的身份验证流。
根据您的需要,您可以使用ClientSecretCredential
。关于如何实施,请参考以下步骤
#create a sevice pricipal and assign Storage Blob Data Contributor role at storage account level
az login
az ad sp create-for-rbac -n "MyApp" --role "Storage Blob Data Contributor" \
--scope "/subscriptions/<subscription>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>" --sdk-auth
# just assign Storage Blob Data Contributor role at storage account level
az role assignment create --assignee <sp_name> --role "Storage Blob Data Contributor role"
--scope "/subscriptions/<subscription>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>"
嗯,我不熟悉python库。但是,设备代码流应该为你的应用程序提供一个刷新令牌,它应该能够在不进行交互的情况下使用该令牌来获取新的访问令牌。。“此凭证不缓存令牌——每个get_令牌(*scopes,**kwargs)调用都会开始一个新的身份验证流。”这是一个很大的缺陷:/谢谢,Jim,但我的用例有点不同。我想要设备流,并希望以后重用其令牌,即使在进程重新启动之后也是如此。这样做的目的是不让用户受到太多的干扰。我希望通过编程接口提供类似azure CLI(“az登录”)的体验。@vitaly根据情况,我认为您需要自己实现设备代码流。关于如何实施,请参阅,我回复了您回答的[此问题的变体][1]。非常感谢。
from azure.identity import ClientSecretCredential
token_credential = ClientSecretCredential(
sp_tenant_id,
sp_application_id,
sp_application_secret
)
# Instantiate a BlobServiceClient using a token credential
from azure.storage.blob import BlobServiceClient
blob_service_client = BlobServiceClient(account_url=self.oauth_url, credential=token_credential)
blobs = blob_service_client.list_containers()
for b in blobs:
print(b)