How to fix custom Azure Function

Wajih Arfaoui 70 Reputation points
2024-01-25T22:13:19.6933333+00:00

Hello everyone, I was trying to create an Azure Function using Python that:

  • obtains a key vault connection using the function app's managed system identity (MSI) (my implementation stores the key vault URL in a function app application setting called KEY_VAULT_URL)
  • obtains the value of the “GoogleAnalytics” secret (the contents of the Google service account's private key JSON file)
  • creates a credential using the service account's private key, scoped to https://www.googleapis.com/auth/analytics.readonly (this scope is required to access the analytics API endpoint)
  • requests an access token from Google's OAuth 2.0 service [line 23] then returns it in a JSON response

The problem is that after creating this function and trying to run it using Azure Data Factory, I got this error and i don't know the reason : Call to provided Azure function 'HttpTrigger1' failed with status-'Unauthorized' while invoking 'GET' on 'https://googleanalyticskpi.azurewebsites.net' and message - 'Invoking Azure function failed with HttpStatusCode - Unauthorized.'. I really need an urgent help on this. Thank you

import logging
import azure.functions as func
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
from google.oauth2 import service_account
import os
import json

def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        # Get the Key Vault URL from the environment variable
        key_vault_url = os.environ["KEY_VAULT_URL"]
        
        # Create a secret client using the DefaultAzureCredential
        credential = DefaultAzureCredential()
        client = SecretClient(vault_url=key_vault_url, credential=credential)
        
        # Retrieve the secret containing the Google service account key
        secret_name = "GoogleAnalytics"
        retrieved_secret = client.get_secret(secret_name)
        key_json = retrieved_secret.value
        
        # Load the service account key and create scoped credentials
        credentials = service_account.Credentials.from_service_account_info(
            json.loads(key_json),
            scopes=["https://www.googleapis.com/auth/analytics.readonly"]
        )
        
        # Request an access token from Google
        token = credentials.get_access_token().token

        # Return the token in the response
        return func.HttpResponse(json.dumps({"token": token}), mimetype="application/json")
    except Exception as e:
        # Log the error and return a 500 server error response
        logging.error(f"Exception: {str(e)}")
        return func.HttpResponse(
            "An error occurred while processing your request.",
            status_code=500
        )
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,911 questions
Azure Data Factory
Azure Data Factory
An Azure service for ingesting, preparing, and transforming data at scale.
11,625 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ryan Hill 30,281 Reputation points Microsoft Employee Moderator
    2024-01-30T17:39:38.6766667+00:00

    Hi @Wajih Arfaoui
    Apologies for the late reply. At first glance, it appears you're not passing the appropriate key to the function. The key/code is required if you don't configure your function for anonymous access. See Manually run a non HTTP-triggered Azure Functions | Microsoft Learn for more information, but you need to add the function key as x-functions-key to the request header.

    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.