简体   繁体   English

未经授权的错误:使用C#查询或保存Dynamics CRM中的联系人/线索

[英]Unauthorized Error: Query or Save Contact/lead in Dynamics CRM Using C#

I am using the following web api to query data from Dynamics CRM 我正在使用以下Web API从Dynamics CRM查询数据

ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential("xxxxx@mydomain.com", "!@Demo1$#2") });
                    client.BaseAddress = new Uri("https://xxxxx.crm.dynamics.com");
                    client.Timeout = new TimeSpan(0, 2, 0);
                    string contactAltUri = client.BaseAddress + "api/data/v9.0/accounts?$select=name&$top=3";
                    HttpResponseMessage createResponseAlt1 = await client.GetAsync(contactAltUri);

Now in object createResponseAlt1 I can see the following Unauthorized error. 现在,在对象createResponseAlt1我可以看到以下未授权错误。 What is the right way to query and save data to Dynamics CRM? 查询并将数据保存到Dynamics CRM的正确方法是什么? I have username, password and Ms crm subdomain url. 我有用户名,密码和女士crm子域网址。

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  x-ms-service-request-id: 4b323404-cc13-407c-bb6d-56b61823ab84
  REQ_ID: 4b323404-cc13-407c-bb6d-56b61823ab84
  AuthActivityId: 85696c96-6803-4664-9391-d28f45d1766a
  NativeWebSession-Version: 2
  Date: Thu, 07 Mar 2019 13:42:36 GMT
  Set-Cookie: ApplicationGatewayAffinity=03da1c2a15fe28b54ffa99b7eab01d12cd9b55dfb1779b6cccce0809ec64f39a;Path=/;Domain=xxxxx.crm.dynamics.com
  Server: 
  WWW-Authenticate: Bearer authorization_uri=https://login.microsoftonline.com/e20b0aa3-6ec3-4272-a76a-aaa32e0f10d6/oauth2/authorize, resource_id=https://xxxxx.crm.dynamics.com/
  Content-Length: 0
}}

Step 1 : Register an app in Azure Active directory (AAD) to get Application Id (aka Client Id). 步骤1 :在Azure Active Directory(AAD)中注册一个应用程序以获取应用程序ID(又名客户端ID)。 Read more 阅读更多

Step 2 : Use the Client Id to get the authentication token using OAuth, as the CRM online needs to authenticate using AAD this is the approach we have to follow. 步骤2 :使用客户端ID通过OAuth获取身份验证令牌,因为在线CRM需要使用AAD进行身份验证,这是我们必须遵循的方法。 Read more 阅读更多

Code sample : 代码示例

        static string serviceUri = "https://yourorg.crmx.dynamics.com/";
        static string redirectUrl = "https://yourorg.api.crmx.dynamics.com/api/data/v9.0/";

        public static string GetAuthToken()
        {

            // 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 = "3oi467rf-2336-4039-b82i-7c5b859c7be0"; // Client ID after app registration
            string userName = "xyz@youOrg.onmicrosoft.com";
            string password = "Password";
            UserCredential cred = new UserCredential(userName, password);

            // Authenticate the registered application with Azure Active Directory.
            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);
            AuthenticationResult result = authContext.AcquireToken(serviceUri, clientId, cred);
            return result.AccessToken;
        }
        public static void RetrieveAccounts(string authToken)
        {
            HttpClient httpClient = null;
            httpClient = new HttpClient();
            //Default Request Headers needed to be added in the HttpClient Object
            httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Set the Authorization header with the Access Token received specifying the Credentials
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);

            httpClient.BaseAddress = new Uri(redirectUrl);
            var response = httpClient.GetAsync("accounts?$select=name").Result;
            if (response.IsSuccessStatusCode)
            {
                var accounts = response.Content.ReadAsStringAsync().Result;
            }
        }

Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM