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.

Azure Functions
Azure Functions

An Azure service that provides an event-driven serverless compute platform.

0 comments No comments

Answer accepted by question author
MayankBargali-MSFT 71,021 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");  

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.