使用 ClientID 使用 ADAL v3 向 Dynamics 365 进行身份验证

Authenticate to Dynamics 365 using ADAL v3 using ClientID

我正在尝试对我们的在线 Dynamics CRM 进行身份验证以使用可用的 API。

我能找到的关于执行此操作的唯一官方文档是:https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/connect-customer-engagement-web-services-using-oauth 然而,这使用了 'AquireToken',它在 ADAL V3 中不再存在,已被替换为 'AcquireTokenAsync'。

这是我第一次处理 ADAL 并尝试进行身份验证,之前只处理过 'HttpWebRequest' 自定义 API。

我目前只是尝试让代码 运行 没有任何错误,使用 docs.microsoft.com 上的内容 我已经尝试将 'AcquireToken' 更改为 'AcquireTokenAsync'。

public void authenticateToCRM()
        {
            // TODO Substitute your correct CRM root service address,   
            string resource = "https://qqqqqqqqq.crm4.dynamics.com";

            // TODO Substitute your app registration values that can be obtained after you  
            // register the app in Active Directory on the Microsoft Azure portal.  
            string clientId = "******-****-*******-*****-****";
            string redirectUrl = "https://qqqqqqqqq.azurewebsites.net";

            // Authenticate the registered application with Azure Active Directory.  
            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);
            AuthenticationResult result = authContext.AcquireTokenAsync(resource, clientId, new Uri(redirectUrl));
        }

这会导致 'AcquireToken' 中的 'clientId' 字符串变量出错,错误是...

"Argument 2: cannot convert from 'string' to 'Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredentials"

和第 3 个变量 'new Uri(redirectUrl)' 的错误...

"Argument 3: cannot convert from 'System.Uri' to 'Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion"

查看 'AuthenticationContext' Class 的文档和 'AcquireTokenAsync' 的用法,许多人将字符串作为第二个参数:https://docs.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.clients.activedirectory.authenticationcontext?view=azure-dotnet

我不知道如何将 ms 文档中显示的 'AcquireToken' 身份验证用法翻译为与 'AcquireTokenAsync'

一起使用
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace MYFORM_Form.Controllers
{
    public class MYController : Controller
    {
        string organizationUrl = "https://yourcrm.dynamics.com";
        string appKey = "*****";
        string aadInstance = "https://login.microsoftonline.com/";
        string tenantID = "myTenant.onmicrosoft.com";
        string clientId = "UserGUID****";
        public Task<String> SendData()
        {
            return AuthenticateWithCRM();
        }

        public async Task<String> AuthenticateWithCRM()
        {
            ClientCredential clientcred = new ClientCredential(clientId, appKey);
            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID);
            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(organizationUrl, clientcred);
            using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new Uri(organizationUrl);
                    httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes  
                    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                    httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                    httpClient.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
                    JObject myContact = new JObject
                        {
                            {"[EntityFieldname]", "[ValueToBeAdded]"}
                        };

                        HttpResponseMessage CreateResponse = await SendAsJsonAsync(httpClient, HttpMethod.Post, "api/data/v8.2/[EntityName]", myContact);

                        Guid applicationID = new Guid();
                        if (CreateResponse.IsSuccessStatusCode)
                        {
                            string applicationUri = CreateResponse.Headers.GetValues("OData-EntityId").FirstOrDefault();
                            if (applicationUri != null)
                                applicationID = Guid.Parse(applicationUri.Split('(', ')')[1]);
                            Console.WriteLine("Account created Id=", applicationID);
                            return applicationID.ToString();
                        }
                        else
                            return null;
                }

        }

        public static Task<HttpResponseMessage> SendAsJsonAsync<T>(HttpClient client, HttpMethod method, string requestUri, T value)
        {
            var content = value.GetType().Name.Equals("JObject") ?
                value.ToString() :
                JsonConvert.SerializeObject(value, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore });

            HttpRequestMessage request = new HttpRequestMessage(method, requestUri) { Content = new StringContent(content) };
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
            request.Headers.Add("User-Agent", "User-Agent-Here");
            return  client.SendAsync(request);
        }
    }
}