0

When attempting to programmatically add/update a function key, I receive the following error:

StatusCode: 401, ReasonPhrase: 'Unauthorized'

Code:

Executing the following code results in the error described above.

static void FunctionKey(string resourceGroupName, string functionAppName, string functionName, NameValuePair kv)
{
    var resource = $"subscriptions/{SubscriptionId.Value}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{functionAppName}/functions/{functionName}/keys/{kv.Name}?api-version=2022-03-01";
    var httpClient = new HttpClient() { BaseAddress = new Uri("https://management.azure.com/") };
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken.Value);
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var json = @"{
                  ""Properties"": {
                    ""Name"": ""ApiKey"",
                    ""Value"": ""some_value""
                  }
                }";

    using (var content = new StringContent(json, Encoding.UTF8, "application/json"))
    {
        var response = httpClient.PostAsync(resource, content).Result;

        if (!response.IsSuccessStatusCode)
            throw new Exception($"Error: Failed to register function key for {functionName}");
    }
}

Research:

I was successful when performing this task in the the documentation emulator.

enter image description here

enter image description here

Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118
  • Is this the exact code? The 404 hints on an incorrect url, and I can see you might have forgotten to replace the values between {xxxx} in the url – Mocas Jan 22 '23 at 22:18
  • I compared the URL in my automated test with the URL in the documentation emulator. They are identical. – Scott Nimrod Jan 23 '23 at 00:27
  • @Mocas - You were right. My test setup was executing the logic before my actual test would execute. This changed the state of things. Now I'm battling a bad request response that I can hopefully resolve. – Scott Nimrod Jan 23 '23 at 00:36
  • I now get a 401 unauthorized. It's probably because my bearer token is empty. – Scott Nimrod Jan 23 '23 at 00:49
  • Update: I fixed the unauthorized and back to 'Not found'. I checked the URL that succeeded with the one that failed and they are still identical. – Scott Nimrod Jan 23 '23 at 01:38
  • Can you try hardcoding the url with the actual values instead of parameterizing it just for once to confirm? – Mocas Jan 23 '23 at 08:30
  • Also, just pass the full address to the PostAsync method – Mocas Jan 23 '23 at 08:32
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/251331/discussion-between-scott-nimrod-and-mocas). – Scott Nimrod Jan 23 '23 at 09:39

1 Answers1

1

I tried to reproduce the same in my environment via Postman and got below results:

When I ran the below query without including bearer token, I got same error with 401 Unauthorized like below:

PUT https://management.azure.com/subscriptions/<subID>/resourceGroups/<rgname>/providers/Microsoft.Web/sites/<funcappname>/functions/<funcname>/keys/<keyname>?api-version=2022-03-01
{
    "Properties": 
        {
            "Name": "keyname",
            "Value": "xxxxxxxxxxxx"
        }
}   

Response:

enter image description here

After passing the token, I'm able to create function key successfully like below:

enter image description here

When I checked the same portal, srikey appeared under function keys like below:

enter image description here

In your case, you are using httpClient.PostAsync which means POST method.

When I used POST method for below query, I too got 404 Not found error like below:

POST https://management.azure.com/subscriptions/<subID>/resourceGroups/<rgname>/providers/Microsoft.Web/sites/<funcappname>/functions/<funcname>/keys/<keyname>?api-version=2022-03-01
{
    "Properties": 
        {
            "Name": "keyname",
            "Value": "xxxxxxxxxxxx"
        }
}   

Response:

enter image description here

To resolve the error, make sure to use PUT method by changing httpClient.PostAsync method to httpClient.PutAsync method.

Reference: HttpClient.PutAsync Method (System.Net.Http) | Microsoft

Sridevi
  • 10,599
  • 1
  • 4
  • 17
  • I have a similar question if you're available: https://stackoverflow.com/questions/75212448/http-post-to-azure-function-using-bearer-token-and-function-key-still-returns-un – Scott Nimrod Jan 23 '23 at 16:36