0

When I try a azure rest api url on azure docs post man, I am able to get a json which has all the resource groups. https://learn.microsoft.com/en-us/rest/api/resources/resourcegroups/list#code-try-0a link

enter image description here

But I am trying it from a ASP.NET MVC Core C# application, I am receiving an empty array.

    public async Task<ResourceGroupModel> GetResourceGroupStatus()
    {
        ResourceGroupModel resourceGroupModel = null;
        try         
        { 
            string requestUrlString = iconfiguration.GetValue<string>("HealthSettings:AzureGetResourcesBySubscriptionURL");
            string azureSubscription = iconfiguration.GetValue<string>("HealthSettings:AzureSubscription");
            string clientId = iconfiguration.GetValue<string>("HealthSettings:ClientId");
            string tenantId = iconfiguration.GetValue<string>("HealthSettings:TenantId");
            string clientSecret = iconfiguration.GetValue<string>("HealthSettings:ClientSecret");
            Uri requestUrl = new Uri(requestUrlString.Replace("{subscriptionId}", azureSubscription));

            string token = await GetAccessToken(tenantId, clientId, clientSecret);

            _httpClient.DefaultRequestHeaders.Remove("Authorization");
            _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            var response = _httpClient.GetAsync(requestUrl);

            if (response.Result.IsSuccessStatusCode)
            {
                var data = response.Result.Content.ReadAsStringAsync();
                resourceGroupModel = ResourceGroupModel.FromJson(data.Result.ToString());
            }
        }
        catch (Exception ex)
        {
        }
        return resourceGroupModel;
    }

Could you please help me to get rid of strange behavior of Azure REST API. Many thanks in advance. :)

Srikanth Y.
  • 73
  • 10

3 Answers3

0

Your service principal does not have access to the resource group.

  1. Log into Azure Portal and select the Resource Group
  2. Select Access control (IAM) from the Blade
  3. On Check access tab, Add a role assignment
  4. Give your service principal a role (Owner/Contributor/Reader)
  5. Assign access to: Azure AD user, group, or service principal
  6. Type your Service Principal name, search and select it then Save.
  7. Wait a couple of minutes and try again calling your API.
0

As Ciubotariu said, your service principal does not have access to the resource group. However, if you only add your service principal to the resource group, you could only get the specify resource group. So, add your service principal to your Subscription. Here are the steps:

1.Go to your subscription, click Access Control> Add(Add role assignment) enter image description here

2.Add your service principal and assign a role to it like Contributor. enter image description here

3.Then you will get all the resource groups for a subscription. enter image description here

Update:

4.Here is the full code I used:

var appId = "xxxxxxxxxxxxxxx";
var secretKey = "xxxxxxxxxxxxxxxxxxxxx";
var tenantId = "xxxxxxxxxxxxxxxxx";
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
ClientCredential clientCredential = new ClientCredential(appId, secretKey);
var tokenResponse = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;
var accessToken = tokenResponse.AccessToken;
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
    var baseUrl = new Uri($"https://management.azure.com/");
    var requestURl = baseUrl +
                    @"subscriptions/xxxxxxxxxxxxxxxx/resourcegroups?api-version=2019-05-01";
    var response = client.GetAsync(requestURl).Result.Content.ReadAsStringAsync().Result;
}
Joey Cai
  • 18,968
  • 1
  • 20
  • 30
  • I have added myself as contributor in IAM of the subscruption, but no luck, I am still receiving an empty array. – Srikanth Y. Jun 13 '19 at 22:10
  • Do you add the service principal you registered in subscription? I recreate a new sp and it works well after several minutes. – Joey Cai Jun 14 '19 at 01:52
0

Deleting the existing clientsecret and creating new one for service principle solved the issue.

Srikanth Y.
  • 73
  • 10