I was able to run the same App a few months ago, by using Microsoft.PowerPlatform.Dataverse.Client.ServiceClient to retrieve the DynamicsCRM entity, for example, "AccountData", but now I am getting this "The HTTP request was forbidden with client authentication scheme 'Anonymous'" even though I logged in via Azure AD (now Entra ID).
I initiated the client:
_serviceClient = new ServiceClient(new Uri(config.Resource), config.ClientId, config.ClientSecret, true);
the Uri to Dynamics CRM service, client id and client secret are all valid, and it worked before I updated all the related NuGet packages to the latest:
Microsoft.AspNetCore.Authentication.JwtBearer (8.06)
Microsoft.AspNetCore.Authentication.OpenIdConnect (8.06)
Microsoft.Identity.Web (2.19.1)
Microsoft.Identity.Web.UI (2.19.1)
Microsoft.PowerPlatform.Dataverse.Client (1.1.22)
Microsoft.PowerPlatform.Dataverse.Client.Dynamics (1.1.22)
public async Task<IReadOnlyList<AccountData>> ReadAccounts(int accountId)
{
var result = new List<AccountData>();
var response = await _serviceClient.RetrieveMultipleAsync(new QueryExpression
{
EntityName = "AccountData",
Distinct = true,
Criteria =
{
Conditions =
{
new ConditionExpression("account_id", ConditionOperator.Equal, accountId)
},
},
ColumnSet = new ColumnSet(allColumns: true)
});
foreach (var entity in response.Entities)
{
AccountData ad = new AccountData(entity);
result.Add(ad);
}
return result;
}
And I was able to access the same service url via directly HttpClient call using access token:
protected override async Task OnInitializedAsync()
{
var config = new DynamicsCrmConfigProvider();
baseApiUrl = config.Resource;
// Get the HttpClient
_httpClient = HttpClientFactory.CreateClient();
try
{
authorizationToken = await TokenAcquisitionService.GetAccessTokenForUserAsync(new string[] { $"{baseApiUrl}user_impersonation" });
}
// Microsoft Identity Web specific exception class for use in Blazor or Razor pages to process the user challenge.
// Handles the MsalUiRequiredException.
catch (MicrosoftIdentityWebChallengeUserException ex)
{
ConsentHandler.HandleException(ex);
}
catch (Exception)
{
throw new Exception("Error getting access token.");
}
// Set the auth token
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authorizationToken);
var url = $"{baseApiUrl}api/data/v9.2/accounts({accountId})";
HttpResponseMessage response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
}
else
{
throw new Exception("Error sending request.");
}
}
I browsed the same questions for multiple times and multiple places but have not come across a satisfactory answer thus far.
What was I missing? I have valid Azure App registration.