0

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#?

  • The answer you mentioned looks correct, could you show the details of your error message instead of something like `but all failed`, `still doesn't work`?They are useless. – Joy Wang Jan 19 '21 at 02:43
  • It doesn't compile. The constructor of SubscriptionClient needs a RestClient as its parameter. – Milhouse Manastorm Jan 19 '21 at 03:17

2 Answers2

1

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

Joy Wang
  • 39,905
  • 3
  • 30
  • 54
  • `SubscriptionClient SubscriptionClient = new SubscriptionClient(serviceClientCredentials);` doesn't compile. What is the namespace of SubscriptionClient? I tried Microsoft.Azure.Management.ResourceManager.Fluent.SubscriptionClient, but it doesn't compile – Milhouse Manastorm Jan 19 '21 at 17:56
  • @MilhouseManastorm Not that, it is `Microsoft.Azure.Management.ResourceManager`, a preview version, nuget https://www.nuget.org/packages/Microsoft.Azure.Management.ResourceManager/ – Joy Wang Jan 20 '21 at 01:16
0

You can try using the REST API Subscriptions - List.

GET https://management.azure.com/subscriptions?api-version=2020-01-01

Request Header:

Authorization: Bearer <access token>

Update:

The simplest way to get access token is open the link Subscriptions - List and sign in with your account.

Then click "try it" at the top right of the script.

enter image description here

You will find the access token in Request preview.

enter image description here

Jane Ma-MSFT
  • 4,461
  • 1
  • 6
  • 12