0
votes

I'm trying to follow some MS docs about using Web API for integrations with Dynamics 365 CRM, but I'm stuck as my organization uses a multi-factor auth method which is not easy to connect to.

I already tried using an app password in the code, but it failed. Already have the app registered on Azure AD, permissions granted, manifest modified, secret-key generated.

Last try I did based on MS docs is

    `using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using System.Net.Http.Headers;
    using System.Net.Http;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Configuration;
    using Newtonsoft.Json;
    using static System.Console;

    namespace CRM_WebApi
    {
    class Program
    {
        static void Main(string[] args)
        {
            string serviceUrl = "https://MY-ORG.api.crm.dynamics.com";
            string clientId = "f8dea8ad-b993-4161-8743-***********X";
            string secret = "X*x*x*x*x*_lm2_DUo.0Dj_5_Wvkgu~eAY4";
            string redirectUrl = "http://localhost";

            AuthenticationContext authContext =
            new AuthenticationContext("https://login.microsoftonline.com/MY-ORG/oauth2/authorize");
            ClientCredential credential = new ClientCredential(clientId, secret);
            AuthenticationResult result = authContext.AcquireToken(serviceUrl, credential);
            //The access token
            string accessToken = result.AccessToken;

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(serviceUrl);
                client.Timeout = new TimeSpan(0, 2, 0);  //2 minutes  
                client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                client.DefaultRequestHeaders.Add("OData-Version", "4.0");
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                HttpRequestMessage request =
                    new HttpRequestMessage(HttpMethod.Get, "/api/data/v9.1/WhoAmI");
                //Set the access token
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;
                if (response.IsSuccessStatusCode)
                {
                    //Get the response content and parse it.  
                    JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                    Guid userId = (Guid)body["UserId"];
                    Console.WriteLine("Your system user ID is: {0}", userId);
                }

              }
            }
        }
    }`

This time I get the token, but get on the response 403-Forbidden.

{StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{ x-ms-service-request-id: 51067dc4-670c-4417-84b6-600044745e18
x-ms-service-request-id: 04dd42b7-898d-4935-9c7e-20c1e7028a10
Strict-Transport-Security: max-age=31536000; includeSubDomains REQ_ID: 04dd42b7-898d-4935-9c7e-20c1e7025b20
AuthActivityId: fb3e62d9-4e1e-405f-846a-711e6ccc5555
X-Source: 18921112101886374119914120471128195219221222118018411711623541331812331911702441xxx* X-Source: 2441011722446104156421301162318117713035251169236256193231163106232101179236129xxx
Public: OPTIONS,GET,HEAD,POST Timing-Allow-Origin: * Date: Fri, 06 Nov 2020 20:56:25 GMT
Set-Cookie: ARRAffinity=f439e98480c5c889aa462a387e36ac04f192110c01737e1e00da32e45cedxx; domain=MY-ORG.api.crm.dynamics.com; path=/; secure; HttpOnly Content-Length: 89 Allow: OPTIONS Allow: GET Allow: HEAD Allow: POST}}

Did anybody face a similar problem? Could you please guide me about to resolve this problem?

1
Hi did you have a chance to look into my answer? If it's helpful, you can mark it as accepted. Thank you.Allen Wu

1 Answers

1
votes

Based on your code, you are referring to this Connect as an app to get the access token.

Please note that the docs states:

When registering an app you follow many of the same steps described in Walkthrough: Register an app with Azure Active Directory, with the following exceptions:

You do not need to grant the Access Dynamics 365 as organization users permission.

This application will be bound to a specific user account.

So you don't need to add the delegated permissions in the Azure AD app. What you need to do is Common Data Service user account bound to the registered app and Manually create a Common Data Service application user.

After that, you can get the access token which has enough permissions.