Skip to content

Instantly share code, notes, and snippets.

@mhagrelius
Created October 2, 2019 20:57
Show Gist options
  • Save mhagrelius/d409b051f68e25593102c6a2d5af9665 to your computer and use it in GitHub Desktop.
Save mhagrelius/d409b051f68e25593102c6a2d5af9665 to your computer and use it in GitHub Desktop.
Get Access Token from Azure AD for Integration Testing
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
namespace Api.Test
{
public static class AuthHelpers
{
public static async Task<string> GetAccessToken()
{
var configuration = new ConfigurationBuilder()
.AddUserSecrets<Startup>()
.AddEnvironmentVariables()
.Build();
using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("client_id", configuration["Testing:client_id"]),
new KeyValuePair<string, string>("client_secret", configuration["Testing:client_secret"]),
new KeyValuePair<string, string>("resource", configuration["Testing:resource"]),
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var response = await client.PostAsync($"https://login.microsoftonline.com/{configuration["Testing:tenant_id"]}/oauth2/token", new FormUrlEncodedContent(values));
var parsedObject = JObject.Parse(await response.Content.ReadAsStringAsync());
return (string)(parsedObject["access_token"]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment