我尝试向我们的在线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));
}
这导致' clientId' ' AcquireToken'中的字符串变量错误是......
"参数2:无法转换为' string'至 ' Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredentials"
和第3个变量的错误'新的Uri(redirectUrl)',...
"参数3:无法转换为System.Uri'至 ' Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion"
查看' AuthenticationContext'的文档。类和使用' AcquireTokenAsync'许多人都有一个字符串作为第二个参数:https://docs.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.clients.activedirectory.authenticationcontext?view=azure-dotnet
我不知道如何使用' AcquireToken'来转换身份验证的用法。 ms文档中显示与' AcquireTokenAsync'
一起使用答案 0 :(得分:3)
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);
}
}
}