Sample code to connect to CDS / Dynamics 365 / CE using OAuth

Sample code for quick reference for connecting to CDS through a console application using OAuth

Add the NuGet package for Microsoft.CrmSdk.XrmTooling.CoreAssembly in the project.

Xrm.Tooling is the preferred way to connect to CDS, because of many benefits – we can define connection string, thread safety, support for X.509 certificate authentication, support for secure storage of sign-in credentials and reuse etc.


Here we will be using the sample AppId and Redirect URI.

Sample Code- 

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System;

namespace SampleConsoleApp
class Program
static void Main(string[] args)
string ConnectionString = "AuthType = OAuth; " +
"Username = [username]@[domain];" +
"Password = [password]; " +
"Url = https://[orgname];" +
"AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;" +
"RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;" +

CrmServiceClient svc = new CrmServiceClient(ConnectionString);

if (svc.IsReady)
var myContact = new Entity("contact");
myContact.Attributes["lastname"] = "Test";
myContact.Attributes["firstname"] = "User1";

For .NET Framework 4.5.2 – we need to explicitly specify Tls1.2 as the default protocol. 

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

.NET Framework 4.6.2 uses TLS 1.2 as the default protocol.


More details on – Connection string parameters.

Sample Code – Dynamics 365 Web API / Organization Service

Hope it helps..


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

11 thoughts on “Sample code to connect to CDS / Dynamics 365 / CE using OAuth”

      1. How Redirect uri is working. I am using .net webform application and trying to get redirected to an aspx page.


Please share your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.