Search code examples
wcfdynamics-crmcrm

CRM 2016 api unauthorized access


I wrote this code to connect to CRM on premise 2016 and retrieve some data.

Here it's

var credentials = new NetworkCredential("username", "password?", "domain");
            var client = new HttpClient(new HttpClientHandler() { Credentials = credentials })
            {
                BaseAddress = new Uri("https://xxxtestenv.elluciancrmrecruit.com/api/data/v8.0/")
            };
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = client.GetAsync("datatel_events?$orderby=datatel_eventname").Result;
            if (response.IsSuccessStatusCode)
            {
                var yourcustomobjects = response.Content.ReadAsStringAsync();
            }

but I get this error

  response    {StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:

{ REQ_ID: b685b007-199b-4a4a-85cc-3a29684e5588 Date: Thu, 22 Sep 2016 19:27:35 GMT Server: Microsoft-IIS/8.5 WWW-Authenticate: Negotiate WWW-Authenticate: NTLM X-Powered-By: ASP.NET Connection: keep-alive Content-Length: 49 Content-Type: text/plain }} System.Net.Http.HttpResponseMessage

Any suggestions?


Solution

  • Try using below code to connect to MS CRM on premise.

    string strOrganizationUri = "https://{your domain}/XRMServices/2011/Organization.svc";
                string strUserName = "{your domain username}";
                string strPassword = "{your domain password}";
                var organizationUriIFD = new Uri(strOrganizationUri);
    
                var credentials = new ClientCredentials();
                credentials.UserName.UserName = strUserName;
                credentials.UserName.Password = strPassword;
    
                IServiceConfiguration<IOrganizationService> config = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(organizationUriIFD);
                IOrganizationService service;
                using (var serviceProxy = new OrganizationServiceProxy(config, credentials))
                {
                    // This statement is required to enable early-bound type support.
                    serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
    
                    service = serviceProxy;
    
                }
    
    
                // Get the ID's of the current user and business unit.
                var who = new WhoAmIRequest();
                //retreive user data from the server.
                var whoResponse = (WhoAmIResponse)service.Execute(who);