1
  • Python 3.11 - Azure Function - Http Trigger
  • Functionality - (packages utilization - Pandas, Numpy, dateutil), Listing blobs
  • IDE - VS Code

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "<storage-acc-conn-str>",
    "FUNCTIONS_WORKER_RUNTIME": "python"
  }
}

init.py:

import logging
import azure.functions as func

import pandas as pd  
import numpy as np

# importing methods from the datetime module as a base.  
import datetime  
# importing several methods from the dateutil subclasses.  
from dateutil.relativedelta import *  
from dateutil.easter import *  
from dateutil.parser import *  
from dateutil.rrule import *

from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    # Code for Pandas Package
    info = np.array(['P','a','n','d','a','s'])  
    a = pd.Series(info)
    print(a)
    
    
    # Creating some datetime objects  
    present_datetime = datetime.datetime.now()  
    print("The Present datetime:", present_datetime)  
    present_date = datetime.date.today()  
    print("The Present date:", present_date)  
    
    account_url = "https://<storageaccname>.blob.core.windows.net"
    default_credential = DefaultAzureCredential()

    # Create the BlobServiceClient object
    blob_service_client = BlobServiceClient(account_url, credential=default_credential)
    container_client = blob_service_client.get_container_client("textfilescontainer")
    print("\nListing blobs...")

    # List the blobs in the container
    blob_list = container_client.list_blobs()
    for blob in blob_list:
        print("\t" + blob.name)
    
    
    
    return func.HttpResponse(f"Hello Hasher, This HTTP triggered function executed successfully.")

requirements.txt:

azure-functions
numpy
pandas
python-dateutil
azure.storage.blob
azure.identity

Role Assignments to the Subscription and Storage Account:

enter image description here

Result:

For detailed output, run func with --verbose flag.
[2023-06-06T08:04:10.811Z] Worker process started and initialized.
[2023-06-06T08:04:12.391Z] Executing 'Functions.HttpTrigger1' (Reason='This function was programmatically called via the host APIs.', 
Id=<alphanumericid)
[2023-06-06T08:04:12.462Z] No environment configuration found.
[2023-06-06T08:04:12.462Z] Python HTTP trigger function processed a request.
[2023-06-06T08:04:12.462Z] ManagedIdentityCredential will use IMDS
[2023-06-06T08:04:12.462Z] Request URL: 'http://ipaddr/metadata/identity/oauth2/token?api-version=REDACTED&resource=REDACTED'Request method: 'GET'
Request headers:
    'User-Agent': 'azsdk-python-identity/1.13.0 Python/3.11.3 (Windows-10-10.0.)'
No body was attached to the request
[2023-06-06T08:04:15.368Z] Host lock lease acquired by instance ID 'alphanumericid'.
[2023-06-06T08:04:16.781Z] DefaultAzureCredential acquired a token from AzurePowerShellCredential
[2023-06-06T08:04:16.782Z] Request URL: 'https://storageaccountname.blob.core.windows.net/textfilescontainer?restype=REDACTED&comp=REDACTED'  
Request method: 'GET'
Request headers:
    'x-ms-version': 'REDACTED'
    'Accept': 'application/xml'
    'User-Agent': 'azsdk-python-storage-blob/12.16.0 Python/3.11.3 (Windows-10-10.0.
    'x-ms-date': 'REDACTED'
    'x-ms-client-request-id': 'alphanumericid'
    'Authorization': 'REDACTED'
No body was attached to the request
[2023-06-06T08:04:17.175Z] Response status: 403
Response headers:
    'Content-Length': '279'
    'Content-Type': 'application/xml'
    'Server': 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0'
    'x-ms-request-id': 'alphanumericid'
    'x-ms-client-request-id': 'alphanumericid'
    'x-ms-version': 'REDACTED'
    'x-ms-error-code': 'AuthorizationPermissionMismatch'
    'Date': 'Tue, 06 Jun 2023 08:04:16 GMT'
[2023-06-06T08:04:17.232Z] Executed 'Functions.HttpTrigger1' (Failed, Id=alphanumericid, Duration=4852ms)
[2023-06-06T08:04:17.234Z] System.Private.CoreLib: Exception while executing function: Functions.HttpTrigger1. System.Private.CoreLib: Result: Failure
Exception: HttpResponseError: This request is not authorized to perform this operation using this permission.

I tried the solution given in this SO Thread but still not working.

Could anyone identify what I'm missing?

  • Some questions: 1) Are you running the code locally or in the cloud? 2) The permissions screenshot you share, who is the user for which the permissions are assigned? – Gaurav Mantri Jun 06 '23 at 08:49
  • Thanks for the prompt response @GauravMantri. 1) Running Locally (in Vs Code) 2) Yes, same user who is the owner of subscription and resources inside it, and that same user is logged in the VS Code also. –  Jun 06 '23 at 08:51
  • This should have worked. Are you on Windows? Please try something - get the token using `var token = default_credential.get_token('https://storage.azure.com/')` and check if the token is issued for correct user. You can use https://jwt.io to parse the token. – Gaurav Mantri Jun 06 '23 at 09:04
  • Yes, it's running on Windows OS. –  Jun 06 '23 at 09:06
  • @GauravMantri, Any practical example or code on how to use `var token = default_credential.get_token('https://storage.azure.com/')` –  Jun 06 '23 at 09:15
  • I referenced this link: https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.defaultazurecredential?view=azure-python. – Gaurav Mantri Jun 06 '23 at 09:20

1 Answers1

0

enter image description here

As you informed in the Comments that the user is Subscription Owner and performing the development operations with the same user, which will not work because that user is an external user.

Check the user principal names of the user you have logged in with, in the Azure Active directory > Users list.

You can and have to perform all these development operations with the user created in your Azure AD domain. For example: `[userhasher@hashorg.onmicrosoft.com]. This UPN (User Principal Name) shouldn't include #EXT word in it.

Dasari Kamali
  • 811
  • 2
  • 2
  • 6