Skip to content

Instantly share code, notes, and snippets.

@ljtill
Last active August 1, 2022 13:11
Provides the ability to generate an Access Token from Azure Active Directory
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
var accessToken = await GetAccessTokenAsync();
async Task<string> GetAccessTokenAsync()
{
/*
* Environment variables
*/
var tenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID");
if (tenantId is null)
{
Console.WriteLine("Environment variable AZURE_TENANT_ID is not set");
Environment.Exit(1);
}
var clientId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
if (clientId is null)
{
Console.WriteLine("Environment variable AZURE_CLIENT_ID is not set");
Environment.Exit(1);
}
var clientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET");
if (clientSecret is null)
{
Console.WriteLine("Environment variable AZURE_CLIENT_SECRET is not set");
Environment.Exit(1);
}
var client = new HttpClient();
client.BaseAddress = new Uri("https://login.microsoftonline.com/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("resource", "https://management.azure.com/")
};
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsync($"{tenantId}/oauth2/token", new FormUrlEncodedContent(body));
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException re)
{
Console.WriteLine(re.Message);
Environment.Exit(1);
}
var data = JsonSerializer.Deserialize<Token>(await response.Content.ReadAsStringAsync());
if (data is null)
{
Console.WriteLine("Failed to deserialize the response");
Environment.Exit(1);
}
return data.AccessToken;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment