How to enumerate Azure subscriptions and tenants programmatically?

吃可爱长大的小学妹 提交于 2019-12-10 23:19:41

问题


How to enumerate Azure subscriptions and tenants programmatically? This is related to my previous question Login-AzureRmAccount (and related) equivalent(s) in .NET Azure SDK.

Basically I try to replicate the behavior of Login-AzureRmAccount and Get-AzureRmSubscription in desktop or a console application. Thus far I've figured out MSAL seems to always require client ID and tenant ID, so there needs to be some other library to acquire those from. After this I would like to go about creating a service principal programmatically using the most current library, but I suppose that is a subject for further investigation (and questions if needed).


回答1:


Actually, the Login-AzureRmAccount and Get-AzureRmSubscription use the Microsoft Azure PowerShell app to operate the Azure resource through Resource Manager REST APIs.

To simulate the same operations using REST as PowersShell commands, we can also use this app. However since this app is register on Azure portal(not the v2.0 app) so we are not able to acquire the token using this app via MSAL. We need to use Adal instead of MSAL.

Here is a code sample to list the subscriptions using admin account via Microsoft.WindowsAzure.Management using this app for your reference:

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);


来源:https://stackoverflow.com/questions/44738024/how-to-enumerate-azure-subscriptions-and-tenants-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!