Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Unanswered

Error accessing Dynamics CRM via Dataverse API, worked but stopped working

Posted on by 22
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. 
 
 
 
  • Alex.P Profile Picture
    Alex.P 66 on at
    Error accessing Dynamics CRM via Dataverse API, worked but stopped working
    Hey there, any luck solving?
    I have the same error for my multitenant app. It works fine with a lot of instances, but fails for one of the customers.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans