Search code examples
c#azuresdksubscription

Authenticate at subscription level using Azure SDK


I'm trying to get a list of App Services from a subscription so that I can filter staging sites and delete them using the Azure SDK. I'm running into the issue of not authenticating properly or not being able to see any resources on the subscription.

I have the "Owner" role on the subscription so I should have total access to the subscription and its resources however when trying to follow Microsoft's docs on authenticating (https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication) I can't seem to find a way to authenticate at the subscription level.

Here's the code I have:

                var azurecreds = SdkContext.AzureCredentialsFactory
                   .FromServicePrincipal(
                       "???",  //client ID
                       "???",  //client secret
                       "have this",  //tenant ID
                       AzureEnvironment.AzureGlobalCloud);

                var azure = Azure
                    .Configure()
                    .Authenticate(azurecreds)
                    .WithSubscription("have this");    //subscription ID

                //attempts with hard-coded values but not working
                var appServicePlans = azure.AppServices.AppServicePlans.List();
                var appServicePlans2 = azure.WebApps.List();
                var appServicePlans2 = azure.AppServices.AppServicePlans.ListByResourceGroup("Staging");

Solution

  • As you are following this document : Authenticate with token credentials

    So , as per the above document , you must have created a service principal using this command :

     az ad sp create-for-rbac --sdk-auth
    

    After you have create this service principal , you will get the below details :

    enter image description here

    From the above picture you have to copy the ClientID, Client Secret, TenantID and SubscriptionId. After you have taken a note of these mentioned details , you can put the same in the code .

    var azurecreds = SdkContext.AzureCredentialsFactory  
    .FromServicePrincipal(  
    "ClientID copied from the above step", //client ID  
    "Client Secret Copied from the above step", //client secret  
    "have this", //tenant ID  
    AzureEnvironment.AzureGlobalCloud);
    
      
    
    var azure = Azure  
    .Configure()  
    .Authenticate(azurecreds)  
    .WithSubscription("have this"); //subscription ID
    
      
    
    //attempts with hard-coded values but not working  
    var appServicePlans = azure.AppServices.AppServicePlans.List();  
    var appServicePlans2 = azure.WebApps.List();  
    var appServicePlans2 = azure.AppServices.AppServicePlans.ListByResourceGroup("Staging");