How do I authenticate a user against an Azure storage blob in python?

廉价感情. 提交于 2019-12-24 10:37:16

问题


I'm looking for a way to authenticate a user against an Azure blob container. The sample code (yep, newbie alert) works just fine, using an access key for the storage account, but that feels uncomfortably like giving away full control of the entire storage account to anyone who steals the credentials.

The auth sample (from https://azure.microsoft.com/en-us/resources/samples/storage-python-getting-started/) looks like this:

block_blob_service = BlockBlobService(account_name='<acc>', account_key='<key>')

I have a service user set up in Active Directory with a role in the storage account restricting its use of the blob container; it's intended to do nothing but write new items into one specific container.

I'd like to use that user's credentials in the python script so that if it leaks, there's no access to other storage resources. Is there a way to generate an access key based on a resource/id combination, or similar way to achieve that? I've been browsing the Azure Python API docs, but not making any headway.

Edit: I've made a little progress. I've created a service principal with appropriate IAM restrictions. That appears to log in successfully when I call this:

credentials = ServicePrincipalCredentials( client_id=<>, secret=<>, tenant=<>)
print(credentials)

Which gives me an object:

<msrestazure.azure_active_directory.ServicePrincipalCredentials object at 0x7f34f52668d0>

And an error if I give it incorrect credentials. So, great, I have a credentials object. Now what? I can't find a way to feed it into BlockBlobService.


回答1:


You could refer to this article to authenticate with Azure Active Directory from an application for access to blobs.

1.Register your application with an Azure AD tenant

2.Grant your registered app permissions to Azure Storage

3.Python code:

import adal
from azure.storage.blob import (
    BlockBlobService,
    ContainerPermissions,
)
from azure.storage.common import (
    TokenCredential
)

RESOURCE = "https://storage.azure.com/"
clientId = "***"
clientSecret = "***="
tenantId = "***"
authority_url = "https://login.microsoftonline.com/" + tenantId

print(authority_url)
context = adal.AuthenticationContext(authority_url)

token = context.acquire_token_with_client_credentials(
    RESOURCE,
    clientId,
    clientSecret)
print(token)

tokenCre = TokenCredential(token["accessToken"])

blobService = BlockBlobService(account_name="***", token_credential=tokenCre)

blobService.list_blobs(container_name="***")
for i in blobService.list_blobs(container_name="***"):
    print(i.properties.name)


来源:https://stackoverflow.com/questions/53906986/how-do-i-authenticate-a-user-against-an-azure-storage-blob-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!