How can I resolve an unauthorized error when using Azure Management API?
Note: I would prefer to resolve this programmatically (in code) instead of running commands/scripts.
Objective:
I need to retrieve function names from a Function App in Azure.
Example:
var current = Pulumi.Azure.Core.GetClientConfig.InvokeAsync().Result;
var subscriptionId = current.SubscriptionId;
var appName = functionApp.Name;
var url = $"GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{appName}/functions?api-version=2022-03-01";
var httpClient = new HttpClient();
var result = await httpClient.GetAsync(url);
if (!result.IsSuccessStatusCode) throw new Exception($"Error: Failed to retrive Azure function names from {appName}");
var json = result.Content.ReadAsStringAsync();
Thoughts:
I think I need to create a bearer token but do not know the steps required.
I tried to reproduce the same in my environment via Postman and got same error as below:
To resolve the error, you need to generate bearer token for the service principal and include it in headers section with Authorization parameter.
I registered one Azure AD application in my tenant like this: Go to Azure Portal -> Azure Active Directory -> App registrations -> New registration
Now, create one client secret in that application and copy its
valuelike below:Make sure to assign proper role based on your requirement. I assigned
Readerrole to the above service principal under my subscription like below:Go to Azure Portal -> Subscriptions -> Your Subscription -> Access control (IAM) -> Add role assignment
In my function app, I created one HTTP function named SriHTTP like below:
Now, I generated access token via Postman with below parameters:
Response:
I got the results successfully when I used the above token to call management API like below:
Response: