使用ClientID使用ADAL v3对Dynamics 365进行身份验证 [英] Authenticate to Dynamics 365 using ADAL v3 using ClientID

查看:97
本文介绍了使用ClientID使用ADAL v3对Dynamics 365进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to authenticate to our online Dynamics CRM to use the available APIs.

我能找到的唯一官方文档是: https://docs.microsoft.com/zh-cn/dynamics365/customer-engagement/developer/connect-customer -engagement-web-services-using-oauth ,但是它使用的 AquireToken在ADAL V3中已不存在,已被 AcquireTokenAsync替换。

The only official documentation on doing this I can find is: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/connect-customer-engagement-web-services-using-oauth this however uses 'AquireToken' which no longer exists in ADAL V3, with it having been replaced with 'AcquireTokenAsync'.

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

This is my first time dealing with ADAL and trying to authenticate, previously only having dealt with 'HttpWebRequest' custom APIs.

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

I'm currently just trying to have the code run without any errors, using what is on docs.microsoft.com I've tried changing 'AcquireToken' to '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字符串变量出错错误是...

This results in an error for the 'clientId' string variable in 'AcquireToken' the error being...


参数2:无法从'string'转换为
'Microsoft.IdentityModel.Clients。 ActiveDirectory.ClientCredentials

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

以及第三个变量'new Uri(redirectUrl)'的错误,

and error on the 3rd variable 'new Uri(redirectUrl)', of...


参数3:无法从'System.Uri'转换为
'Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion

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

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

Looking at the documentation for 'AuthenticationContext' Class and the usage of 'AcquireTokenAsync' many have a string as the 2nd argument: https://docs.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.clients.activedirectory.authenticationcontext?view=azure-dotnet

我不知道如何转换ms文档中显示的 AcquireToken身份验证的用法,以与 AcquireTokenAsync'

I do not know how to translate the usage for authentication with 'AcquireToken' shown in the ms docs to use with '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);
        }
    }
}

这篇关于使用ClientID使用ADAL v3对Dynamics 365进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆