Skip to content

Instantly share code, notes, and snippets.

@Ercenk
Last active March 23, 2022 18:56
Show Gist options
  • Save Ercenk/28e007ebd846a2ed87149a72ee858c4b to your computer and use it in GitHub Desktop.
Save Ercenk/28e007ebd846a2ed87149a72ee858c4b to your computer and use it in GitHub Desktop.
Get an Azure management client in C# using az CLI app ID and interactive login
IAzure GetAzureClient()
{
// az CLI app Id - DO NOT CHANGE THIS
const string clientId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46";
// Change those for your specific Azure subscription.
// TenantId is the directory id of the account you log in to for access your subscription
const string tenantId = "......";
const string subscriptionId = "....";
var appClient = PublicClientApplicationBuilder
.Create(clientId)
.WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
.WithRedirectUri($"http://localhost:3110")
.Build();
var accounts = appClient.GetAccountsAsync().GetAwaiter().GetResult();
string[] scopes = new string[] { "https://management.azure.com/user_impersonation" };
var token = appClient
.AcquireTokenInteractive(scopes)
.WithAccount(accounts.FirstOrDefault())
.ExecuteAsync()
.GetAwaiter()
.GetResult();
var tokenCreds = new TokenCredentials(token.AccessToken);
var azureCredentials = new AzureCredentials(tokenCreds, tokenCreds, tenantId, AzureEnvironment.AzureGlobalCloud);
var restClient = RestClient
.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.WithCredentials(azureCredentials)
.Build();
var azure = Microsoft.Azure.Management.Fluent.Azure
.Authenticate(restClient, tenantId)
.WithSubscription(subscriptionId);
return azure;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment