Last active
September 14, 2020 03:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More details can be found at: https://blog.aggregatedintelligence.com/2020/09/d365-finance-and-operations-odata-query.html