odatadynamics-crmdynamics-365microsoft-dynamics-webapi

Authenticate to Dynamics 365 On premise


I am trying connect to Dynamics 365 On-premise with the OData client for .net

I tried to authenticate through basic authentication, however this is not working.

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)
{

}

The error I recieve is: HTTP Error 401 - Unauthorized: Access is denied

Can someone help me how this is done?


Solution

  • In general I only use the OData client from JavaScript. When using .NET, I use the SDK libraries that provide authentication and access via the CrmServiceClient class.

    To use the OData client from C#, this article outlines the various authentication methods: 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.