403 Error Using Managed Identity in Azure Function App for Blob Storage Access

sunnyegg 40 Reputation points
2025-03-19T06:56:30.5333333+00:00

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
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,703 questions
0 comments No comments
{count} votes

Accepted answer
  1. Achraf Ben Alaya 1,301 Reputation points MVP
    2025-03-19T09:49:43.3033333+00:00

    Hello ,

    I think you need to use :

    credential = ManagedIdentityCredential()

    instead of DefaultAzureCredential .

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.


0 additional answers

Sort by: Most helpful

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.