I am trying to connect to an application registered at MS Azure that enables me to retrieve information from CRM (connecting to D365). I am using HttpClient library. When I try to send a GET method to retrieve information about a client, it gives me StatusCode 403: Forbidden.
Does someone know what could cause the problem? I used Microsoft.PowerPlatform.Dataverse.Client.ServiceClient before System.Net.Http.HttpClient, and it kept giving me reponse code AADSTS7000218. However, I provided the same client ID and secret which I am providing in HttpClient as well. Thank you in advance!
Code:
string authority = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authority))
.Build();
string[] scopes = new string[] { $"{crmUrl}/.default" };
var authResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();
string accessToken = authResult.AccessToken;
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri($"{crmUrl}");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string query = $"/api/data/v9.0/contacts?$filter=mobilephone eq '999999999'";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, httpClient.BaseAddress.ToString() + query);
var response = await httpClient.SendAsync(request);
MS Azure app has default client type enabled, client secret was created two weeks ago and it expires in 2026.
I figured out what was wrong. MS Azure application had redirect URI, but I picked the wrong platform. I was supposed to pick mobile / desktop application, but I chose Web. I've input the same redirect URI and now I am able to connect to MS Azure app from my desktop app.