首页 > 解决方案 > 获取一个用户所属的所有租户的所有订阅

问题描述

当我们对 Azure 帐户使用 Azure CLI 命令az login时,我们可以获取用户所属的所有租户中的所有订阅。现在我想用 Azure .net sdk 来实现它。但我只能获得一个租户的订阅。有人可以帮助我吗?

var cred= SdkContext.AzureCredentialsFactory.FromDevice("app id", "common",AzureEnvironment.AzureGlobalCloud, code =>
            {
                Console.WriteLine(code.Message);
                return true;
            });

            var azure = Azure.Authenticate(cred);
            var subs = azure.Subscriptions.List();
            foreach (var sub in subs) {

                Console.WriteLine(sub.DisplayName);
            }

标签: .netazure

解决方案


azure.Subscriptions.List()只会列出一个租户中的订阅。即使你使用common参数,实际上它也会指定一个默认租户,而不是所有租户。

您可以尝试如下代码,它列出了所有租户并调用 REST API 以列出用户可以访问的每个租户中的所有订阅。

注意:我使用的客户端ID是Microsoft Application Microsoft Azure CLI,您可以04b07795-8ddb-461a-bbee-02f9e1bf7b46直接使用,无需更改为您的。只需运行以下代码,无需更改任何内容。

在此处输入图像描述

using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using System;
using Microsoft.Azure.Services.AppAuthentication;
using System.Net.Http;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var cred = SdkContext.AzureCredentialsFactory.FromDevice("04b07795-8ddb-461a-bbee-02f9e1bf7b46", "common", AzureEnvironment.AzureGlobalCloud, code =>
            {
                Console.WriteLine(code.Message);
                return true;
            });

            var azure = Azure.Authenticate(cred);
            var tenants = azure.Tenants.List();

            foreach (var tenant in tenants)
            {


               string authority = "https://login.microsoftonline.com/" + tenant.TenantId;

                var authContext = new AuthenticationContext(authority);
                AuthenticationResult result = authContext.AcquireTokenAsync("https://management.azure.com/", "04b07795-8ddb-461a-bbee-02f9e1bf7b46", new Uri("http://localhost:80"), new PlatformParameters(PromptBehavior.Auto)).Result;
                //AuthenticationResult result = authContext.AcquireTokenByDeviceCodeAsync(devcode).Result;



                using (var client = new HttpClient()) {
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + result.AccessToken);
                    client.DefaultRequestHeaders.Accept.Clear();
                    //GET Method  
                    HttpResponseMessage response = client.GetAsync("https://management.azure.com/subscriptions?api-version=2019-06-01").GetAwaiter().GetResult();
                    if (response.IsSuccessStatusCode)
                    {

                        //Console.WriteLine(response.Content.ReadAsStringAsync().Result.ToString());
                        string myjson = response.Content.ReadAsStringAsync().Result.ToString();

                        JObject jo1 = (JObject)JsonConvert.DeserializeObject(myjson);
                        string s1 = jo1["value"].ToString();

                        JArray ja2 = (JArray)JsonConvert.DeserializeObject(s1);
                        if (ja2.Count != 0)
                        {
                            for(int i=0;i<ja2.Count;i++)
                            {
                                string j1 = ja2[i]["displayName"].ToString();
                                Console.WriteLine(j1);
                            }                            
                        }
                    }
                    else
                    {
                        Console.WriteLine("Internal server Error");
                    }
                }
            }

            Console.ReadLine();

        }
    }
}

在此处输入图像描述


推荐阅读