Encountering a 403 This request is not authorized to perform this operation. error while using an Azure Function App on a consumption plan to connect to a Storage Account via managed identity. The system managed identity has been enabled, and the Storage Blob Data Owner role has been assigned to the function app. Additionally, the option Allow Azure services on the trusted services list to access this storage account. has been checked.
The error occurs when executing this line:
blob_client.upload_blob(blob_data, overwrite=True)
Here's the relevant code being used:
import azure.functions as func
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
import logging
def main(req: func.HttpRequest) -> func.HttpResponse:
"""HTTP trigger to upload a blob to Azure Blob Storage."""
logging.info("HTTP trigger function received a request.")
try:
try:
req_body = req.get_json()
except ValueError:
logging.error("Invalid JSON in request body.")
return func.HttpResponse(
"Invalid JSON in request body.",
status_code=400
)
blob_name = req_body.get('blob_name')
blob_data = req_body.get('blob_data')
if not blob_name or not blob_data:
logging.error("Missing required fields: 'blob_name' and/or 'blob_data'.")
return func.HttpResponse(
"Request body must contain 'blob_name' and 'blob_data'.",
status_code=400
)
upload_blob_to_target_storage(blob_name, blob_data)
logging.info(f"Successfully uploaded blob: {blob_name}")
return func.HttpResponse(f"Successfully uploaded blob: {blob_name}", status_code=200)
except Exception as e:
logging.error(f"Error: {str(e)}")
return func.HttpResponse(f"Error: {str(e)}", status_code=500)
def upload_blob_to_target_storage(blob_name, blob_data):
"""Uploads a blob to Azure Blob Storage."""
try:
credential = DefaultAzureCredential()
storage_account_name = "# Enter your storage account name here"
container_name = "# Enter your container name here"
blob_service_client = BlobServiceClient(
account_url=f"https://{storage_account_name}.blob.core.windows.net",
credential=credential
)
container_client = blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(blob_name)
blob_client.upload_blob(blob_data, overwrite=True)
logging.info(f"Blob '{blob_name}' uploaded successfully to container '{container_name}'.")
except Exception as e:
logging.error(f"Failed to upload blob '{blob_name}': {str(e)}")
raise