Last active
March 23, 2022 18:56
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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