How to connect to BlobServiceClient in Azure sdk for python using access token on behalf of user generated with the help of msal

Ashish Singh 0 Reputation points
2023-03-20T12:16:05.57+00:00

I am try to use the below code to connect to storage account blobs using the access token that has been generated against the below scope :

> scopes : ['https://storage.azure.com/user_impersonation']
> ```
> 
> 
>  access token is correct since i am able to call the rest api for storage account to list the containers. But below code does not works as expected. Any help on this will be super helpful !!:
> 
```python
> 
> def list_containers_(access_token, page=1, page_size=10):
> 	try:
> 		account_url = "https://{}.blob.core.windows.net".format("userdatastore")
> 		blob_svc = BlobServiceClient(account_url=account_url, credential=access_token)
> 		
> 		containers = blob_svc.list_containers(include_metadata=True)
> 		total_length = 0
> 
> 		container_data=[]
> 		
> 		for i in containers:
> 			if i["name"] in ["azure-webjobs-hosts", "azure-webjobs-secrets"]:
> 				continue
> 			i["metadata"]["name"] = i["name"]
> 			i["metadata"]["size"] = container_size(blob_svc, i["name"])
> 			container_data.append(i["metadata"])
> 			total_length += 1
> 
> 
> 		start_idx = (page - 1) * page_size
> 		end_idx = start_idx + page_size
> 		paginated_container_data = container_data[start_idx:end_idx]
> 
> 		return paginated_container_data, {"total_length": total_length, "page_no": page, "page_size": page_size}
>     
> 	except Exception as e:
> 	    return str(e), 400
> ```
> 
> 
> 

Azure Storage
Azure Storage
Globally unique resources that provide access to data management services and serve as the parent namespace for the services.
3,529 questions
Azure Role-based access control
Azure Role-based access control
An Azure service that provides fine-grained access management for Azure resources, enabling you to grant users only the rights they need to perform their jobs.
968 questions
Microsoft Security Microsoft Entra Microsoft Entra ID
{count} votes

1 answer

Sort by: Most helpful
  1. SaiKishor-MSFT 17,336 Reputation points
    2023-03-29T08:17:09.4+00:00

    @Ashish Singh Thanks for reaching out to Microsoft Q&A.

    It seems like you are trying to list the containers in the Azure Blob Storage using the access token. The code seems to be working fine, but it is missing the import statement for the BlobServiceClient class. You need to add the following import statement at the top of your code: python from azure.storage.blob import BlobServiceClient Also, it is recommended to wrap the code in a try-except block to handle exceptions and return a meaningful error message to the user.

    Please try the above and let me know if it displays the error message in more detail so we can go from there. Thanks!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.