Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@rajrao rajrao commented Sep 14, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.