Skip to content

Instantly share code, notes, and snippets.

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:
var baseUrl = ""; //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 = $"{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)");
var responseBodyAsText = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(response.StatusCode + Environment.NewLine + response.ReasonPhrase);
Copy link

rajrao commented Sep 14, 2020

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