Search code examples
azureazure-devopsazure-active-directoryazure-cliazure-authentication

How to list subscriptions with current azure credential (without registering app) using C#


I am trying to create multiple VMs to multiple Subscriptions programmatically. So I need to list all subscriptions that I can access. But I cannot grant permissions to registered app, so I have to use my own Azure credential.

Then I tried

var subscriptionClient = new Microsoft.Azure.Management.ResourceManager.Fluent.SubscriptionClient(new DefaultAzureCredential());

and

var subscriptionClient = new Microsoft.Azure.Management.ResourceManager.Fluent.SubscriptionClient(new UserPasswordCredential(username,password));

but none of them compiles.

The answer of question How to list subscriptions with Microsoft.Azure.ResourceManager? is almost the answer of my question, but I cannot add comment to ask more question about it.

I installed Microsoft.IdentityModel.Clients.ActiveDirectory version 3.13.2.870 and tried:

 var ctx = new AuthenticationContext("https://login.microsoftonline.com/common");

but ctx doesn't have AcquireToken, it only has AcquireTokenAsync. Unfortunately the following code still doesn't work

var mainAuthRes = await context.AcquireTokenAsync(m_resource, m_clientId, new Uri(m_redirectURI), PromptBehavior.Always);

The compiler says the fourth parameter is wrong which means

context.AcquireTokenAsync(string resource, string client , Uri uri , PromptBehavior promptBehavior )

is not a valid method.

Is there any way to list subscriptions with my current azure credential (without registering app) using C#?


Solution

  • Try the code works for me, it uses the VisualStudioCredential of Azure.Identity to auth, it will list all the subscriptions in all the AAD tenants that you can access(the user account logged in VS).

    using Azure.Core;
    using Azure.Identity;
    using Microsoft.Azure.Management.ResourceManager;
    using Microsoft.Rest;
    using System;
    using System.Threading;
    
    namespace ConsoleApp2
    {
        class Program
        {
            public static void Main(string[] args)
            {
                VisualStudioCredential tokenCredential = new VisualStudioCredential();
                TokenRequestContext requestContext = new TokenRequestContext(new string[] { "https://management.azure.com" });
                CancellationTokenSource cts = new CancellationTokenSource();
                var accessToken = tokenCredential.GetToken(requestContext, cts.Token);
                ServiceClientCredentials serviceClientCredentials = new TokenCredentials(accessToken.Token);
                SubscriptionClient SubscriptionClient = new SubscriptionClient(serviceClientCredentials);
                var tenants = SubscriptionClient.Tenants.List();
                foreach (var tenant in tenants)
                {
                    //Console.WriteLine(tenant.TenantId);
                    VisualStudioCredentialOptions visualStudioCredentialOptions = new VisualStudioCredentialOptions{ TenantId = tenant.TenantId };
                    VisualStudioCredential tokenCredential1 = new VisualStudioCredential(visualStudioCredentialOptions);
                    TokenRequestContext requestContext1 = new TokenRequestContext(new string[] { "https://management.azure.com" });
                    CancellationTokenSource cts1 = new CancellationTokenSource();
                    var accessToken1 = tokenCredential1.GetToken(requestContext, cts1.Token);
                    ServiceClientCredentials serviceClientCredentials1 = new TokenCredentials(accessToken1.Token);
                    SubscriptionClient SubscriptionClient1 = new SubscriptionClient(serviceClientCredentials1);
                    var subs = SubscriptionClient1.Subscriptions.List();
                    foreach (var sub in subs)
                    {
                        //Console.WriteLine(sub.DisplayName);
                        Console.WriteLine($"SubscriptionName : {sub.DisplayName}");
                        Console.WriteLine($"SubscriptionId   : {sub.SubscriptionId}");
                        Console.WriteLine($"TenantId         : {tenant.TenantId}");
                        Console.WriteLine($"State            : {sub.State}");
                        Console.WriteLine();
                    }
    
                }
            }
                
        }
    }
    

    enter image description here