Skip to content

Instantly share code, notes, and snippets.

@rajrao
Last active September 14, 2020 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajrao/455963f9bd5b9a16558b6085116b3c03 to your computer and use it in GitHub Desktop.
Save rajrao/455963f9bd5b9a16558b6085116b3c03 to your computer and use it in GitHub Desktop.
Shows how to perform authentication and retrieval of data from D365 Finance and Operations using OData and the Service to service calls using client credentials
//more details at: https://blog.aggregatedintelligence.com/2020/09/d365-finance-and-operations-odata-query.html
var baseUrl = "https://myDomain.sandbox.operations.dynamics.com"; //a trailing slash here will cause a "No P3P Policy defined" error
var tenantId = "TENANTID AS A GUID HERE";
string applicationId = "APPLICATION GUID HERE";
string clientSecret = "CLIENT SECRET HERE";
string api = "data/";
var authorityUrl = $"https://login.windows.net/{tenantId}";
AuthenticationContext authContext = new AuthenticationContext(authorityUrl);
Task<AuthenticationResult> taskResult = authContext.AcquireTokenAsync(baseUrl, new ClientCredential(applicationId, clientSecret));
AuthenticationResult result = taskResult.Result;
using (var httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes
string authorizationHeader = result.CreateAuthorizationHeader();
httpClient.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, url);
req.Method = HttpMethod.Get;
// Wait for the web service response.
HttpResponseMessage response;
Stopwatch stopwatch = Stopwatch.StartNew();
response = httpClient.SendAsync(req).Result;
if (response.IsSuccessStatusCode)
{
stopwatch.ElapsedMilliseconds.Dump("Result returned (ms)");
stopwatch.Restart();
var responseBodyAsText = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseBodyAsText);
}
else
{
Console.WriteLine(response.StatusCode + Environment.NewLine + response.ReasonPhrase);
}
}
@rajrao
Copy link
Author

rajrao commented Sep 14, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment