Recently we had a requirement to call graph API and CRM web API from custom code. Microsoft has provided us with the ADAL library to get the token from Azure AD. In today’s blog I will share code to get Azure AD access token without ADAL library.
The benefit of getting Azure AD access token is that you will not have to use ILMerge to merge ADAL library in your plugin.
/FOLLOW THE STEPS HERE TO REGISTER AN APPLICATION IN AZURE AD
//AND CREATE AN APPLICATION USER IN CRM
https://msdn.microsoft.com/en-us/library/mt790171.aspx
//This was registered in Azure AD as a WEB APPLICATION AND/OR WEB API
Code snippet
private static async Task GetToken()
{
using (HttpClient httpClient = new HttpClient())
{
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("resource", Resource),
new KeyValuePair<string, string>("client_id", ClientId),
new KeyValuePair<string, string>("client_secret", ClientSecret),
new KeyValuePair<string, string>("grant_type", "client_credentials")
});
HttpResponseMessage response = await httpClient.PostAsync(Authority, formContent);
return !response.IsSuccessStatusCode ? null
: response.Content.ReadAsStringAsync().Result;
}
}
//Parse Access token from the response
//Deserialize the token response to get the access token
var getTokenTask = Task.Run(async () => await GetToken());
Task.WaitAll(getTokenTask);
if (getTokenTask.Result == null)
return;
TokenResponse tokenResponse = JsonConvert.DeserializeObject(getTokenTask.Result);
_accessToken = tokenResponse.access_token;
Hope this helps!
One thought on “{Dynamics 365 CRM WEB API C#} Get Azure AD Access Token without ADAL library”