I have entered the authentication information and am attempting to make a connection to the Business Central service; however, I am receiving an error. On the other hand, when I test it out on Postman, it works without a hitch.
I'm sure I'm overlooking something obvious, and I'm hoping that you can shed some light on the situation for me. The following is an example of the code that I have so far:
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.Identity.Client;
private void BusinessCentral()
{
string TenantId = "...";
string ClientId = "...";
string ClientSecret = "...";
string CallbackUrl = @"https://businesscentral.dynamics.com/";
string GetUrl = string.Format(@"https://api.businesscentral.dynamics.com/v2.0/{0}/Production/api/v2.0/companies", TenantId);
try
{
string[] Scopes = new[] { "https://api.businesscentral.dynamics.com/.default" };
var App = ConfidentialClientApplicationBuilder
.Create(ClientId)
.WithClientSecret(ClientSecret)
.WithRedirectUri(CallbackUrl)
.WithTenantId(TenantId)
.Build();
var result = App.AcquireTokenForClient(Scopes).ExecuteAsync().Result;
if (result != null)
{
HttpClient HttpCli = new HttpClient();
var defaultRequestHeaders = HttpCli.DefaultRequestHeaders;
if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpCli.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequestHeaders.Add("Authorization", result.CreateAuthorizationHeader());
HttpResponseMessage response = HttpCli.GetAsync(GetUrl).Result;
if (response.IsSuccessStatusCode)
{
string json = response.Content.ReadAsStringAsync().Result;
var apiResult = JsonConvert.DeserializeObject<List<JObject>>(json);
}
else
{
string content = response.Content.ReadAsStringAsync().Result;
// ERROR: "code": "Authentication_InvalidCredentials", "message":"The server has rejected the client credentials.
}
}
}
catch (Exception ex)
{
}
}
The following is an example of the error that it gives back:
{"error":{"code":"Authentication_InvalidCredentials","message":"The server has rejected the client credentials. CorrelationId: 161ce9f5-f2f7-4f56-ad1e-b5a7a159292e."}}
Referral link: Github: active-directory-dotnetcore-daemon-v2
Here's a link that may help you.
Step by step to connect to D365 with a client secret to use APIs | Dynamics Chronicles (dynamics-chronicles.com)