对 Dynamics 365 On premise 进行身份验证

Authenticate to Dynamics 365 On premise

我正在尝试使用 .net 的 OData 客户端连接到 Dynamics 365 On-premise

我尝试通过基本身份验证进行身份验证,但这不起作用。

var c = new Microsoft.Dynamics.CRM.System(new Uri("https://mycrm01/crm/api/data/v8.2/"));

c.SendingRequest2 += (o, requestEventArgs) => {
     var creds = username + ":" + password;
     var encodedCreds = Convert.ToBase64String(Encoding.ASCII.GetBytes(creds));
     requestEventArgs.RequestMessage.SetHeader("Authentication", "Basic" + encodedCreds);
};

var contacts = c.Contacts.Where(x => x.Firstname=="testuser");
foreach (var contact in contacts)
{

}

我收到的错误是:HTTP 错误 401 - 未经授权:访问被拒绝

谁能帮我看看这是怎么做到的?

一般来说,我只使用 JavaScript 的 OData 客户端。使用 .NET 时,我使用通过 CrmServiceClient class.

提供身份验证和访问的 SDK 库

要从 C# 使用 OData 客户端,本文概述了各种身份验证方法:https://msdn.microsoft.com/en-us/library/mt595798.aspx

Web API authentication patterns

There are three different ways to manage authentication when using the Web API. With JavaScript in web resources

When you use the Web API with JavaScript within HTML web resources, form scripts, or ribbon commands you don’t need to include any code for authentication. In each of these cases the user is already authenticated by the application and authentication is managed by the application. With on-premises deployments

When you use the Web API for on-premises deployments you must include the user’s network credentials. The following example is a C# function that will return an HttpClient configured for a given user’s network credentials: C#

private HttpClient getNewHttpClient(string userName,string
password,string domainName, string webAPIBaseAddress) {
HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential(userName, password, domainName)
 });
 client.BaseAddress = new Uri(webAPIBaseAddress);
 client.Timeout = new TimeSpan(0, 2, 0);
return client; 
}   

With Microsoft Dynamics 365 (online) or internet facing deployments

When you use the Web API for Dynamics 365 (online) or an on-premises Internet-facing deployment (IFD) you must use OAuth as described in Connect to Microsoft Dynamics 365 web services using OAuth.

If you’re creating a single page application (SPA) using JavaScript you can use the adal.js library as described in Use OAuth with Cross-Origin Resource Sharing to connect a Single Page Application to Microsoft Dynamics 365.