Why does Azure Funtion http request triggered on a timer return access denied 401?

Be The Code 86 Reputation points
2021-09-29T16:49:03.907+00:00

The fact that the http request occurs on a timer trigger probably has very little to do with the issue but is mentioned so that there is a distinction that it is not a function httptrigger.

The url has a request header that is required ("SomeHeaderKey", "SomeHeaderValue").

When performing a curl command on a url to api located in APIm (API management) there is 200 ok response.

When adding the same address with the same header within an Azure Function, I get a 401 (Access Denied).

The header key and value is the same for both the curl command and the Azure Function but wondering if that has something to do with it or is the Azure Function needing some other additional authentication. The api in APIm is taking the url as a parameter to call along with the header. The function is written in c# and here is the section of code:
using System.Net.Http;
using System.Net.Http.Headers;

public async static Task RunAvailabilityTestAsync(ILogger log)
{
   public async static Task RunAvailabilityTestAsync(ILogger log)
   {
      using (var httpClient = new HttpClient())
      {
         httpClient.DefaultRequestHeaders.Authorization = 
            new AuthenticationHeaderValue("SomeHeaderKey", "SomeHeaderValue");

         await httpClient.GetStringAsync("https://api.someaddresstoAPIm.com/?url=http://someaddress.to.request");
      }
   }
}
Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,447 questions
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,911 questions
0 comments No comments
{count} votes

Accepted answer
  1. MayankBargali-MSFT 70,936 Reputation points Moderator
    2021-09-30T09:08:53.9+00:00

    @Be The Code As you are calling the APIM service you need to pass the Ocp-Apim-Subscription-Key header to authenticate the request.
    In your code you are passing the AuthenticationHeaderValue which creates the header as below:
    Authorization: SomeHeaderKey SomeHeaderValue

    The right header that APIM accepts is:
    Ocp-Apim-Subscription-Key : yourSubcriptionKey

    You need to replace this code : httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SomeHeaderKey", "SomeHeaderValue"); with the below code to pass the right headers.

    httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "yourSubscriptionKey");  
    

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.