如何以编程方式枚举 Azure 订阅和租户?

2024-02-19

如何以编程方式枚举 Azure 订阅和租户?这与我之前的问题有关.NET Azure SDK 中的登录-AzureRmAccount(及相关)等效项 https://stackoverflow.com/questions/44619481/login-azurermaccount-and-related-equivalents-in-net-azure-sdk.

基本上我尝试复制的行为Login-AzureRmAccount and Get-AzureRmSubscription在桌面或控制台应用程序中。到目前为止我已经弄清楚了MSAL https://github.com/AzureAD/microsoft-authentication-library-for-dotnet似乎总是需要客户端 ID 和租户 ID,因此需要其他一些库来获取这些内容。之后,我想使用最新的库以编程方式创建一个服务主体,但我认为这是一个需要进一步调查的主题(如果需要的话还会提出问题)。


事实上,Login-AzureRmAccount and Get-AzureRmSubscription使用微软Azure PowerShell应用程序通过以下方式操作Azure资源资源管理器 REST API https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-rest-api.

要使用 REST 作为 PowersShell 命令来模拟相同的操作,我们也可以使用此应用程序。但是,由于此应用程序是在 Azure 门户(而不是 v2.0 应用程序)上注册的,因此我们无法通过 MSAL 使用此应用程序获取令牌。我们需要使用Adal https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/而不是 MSAL。

这是一个代码示例,用于通过以下方式列出使用管理员帐户的订阅Microsoft.WindowsAzure.管理 https://www.nuget.org/packages/Microsoft.WindowsAzure.Management/使用此应用程序供您参考:

public static void ListSubscriptions()
{
     string authority = "https://login.microsoftonline.com/common";
     string resource = "https://management.core.windows.net/";
     string clientId = "1950a258-227b-4e31-a9cf-717495945fc2";
    Uri redirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob");
    AuthenticationContext authContext = new AuthenticationContext(authority);
    var access_token = authContext.AcquireTokenAsync(resource, clientId, redirectUri, new PlatformParameters (PromptBehavior.Auto)).Result.AccessToken;

    var tokenCred = new Microsoft.Azure.TokenCloudCredentials(access_token);
    var subscriptionClient = new SubscriptionClient(tokenCred);
    foreach (var subscription in subscriptionClient.Subscriptions.List())
    {
        Console.WriteLine(subscription.SubscriptionName);
    }
}

Update:

string resource = "https://management.core.windows.net/";
string clientId = "1950a258-227b-4e31-a9cf-717495945fc2";
string userName = "";
string password = "";

HttpClient client = new HttpClient();
string tokenEndpoint = "https://login.microsoftonline.com/common/oauth2/token";
var body = $"resource={resource}&client_id={clientId}&grant_type=password&username={userName}&password={password}";
var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

var result = client.PostAsync(tokenEndpoint, stringContent).ContinueWith<string>((response) =>
{
    return response.Result.Content.ReadAsStringAsync().Result;
}).Result;

JObject jobject = JObject.Parse(result);
var token = jobject["access_token"].Value<string>();

client.DefaultRequestHeaders.Add("Authorization", $"bearer {token}");
var subcriptions = client.GetStringAsync("https://management.azure.com/subscriptions?api-version=2014-04-01-preview").Result;

Console.WriteLine(subcriptions);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何以编程方式枚举 Azure 订阅和租户? 的相关文章

随机推荐