Tip #1339: The easiest CDS/Dynamics 365/CRM connection ever

Question

I need to write a small console app that can authenticate to an online CRM instance with multi-factor authentication turned on. Can anyone point me in the right direction on how to accomplish this?

Stephen Smith

We’ve been through the topic of connections a few times before but this conversation is just too good to pass.

Answer

Scott Durow

Man of few words, mostly keywords, Scott connects in, technically, 3 lines of code.

using Microsoft.Xrm.Tooling.Connector;

var connectionString = @"
AuthType=OAuth;
Username=<username>;
Url=https://<yourorg>.crm.dynamics.com;
AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;
RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;
TokenCacheStorePath=c:\MyTokenCache;
LoginPrompt=Auto";

var client = new CrmServiceClient(connectionString);
if (client.IsReady)
{
    Console.WriteLine("OK");
}
else
{
    Console.WriteLine(client.LastCrmError);
}

[Don’t forget to] Add Nuget package Microsoft.CrmSdk.XrmTooling.CoreAssembly

Scott… this is beautiful. Thanks. ScottObj.BeersOwed++;

Stephen Smith

Marius Agur

Once bitten twice shy Marius delivers a good reminder.

Change this:

LoginPrompt=Auto

to this:

LoginPrompt=Always

if you are logged in with with an org account and need to log in to an instance with other credentials. Otherwise SSO will mess up your life.

Tîpp Jäår $0.02 + GST

What are those GUIDs used in AppId and RedirectUri? They are special test values as defined in the official docs. You should really get and use your own.

If you are connecting / reconnecting to multiple instances, don’t forget to add RequireNewInstance=true; which we did talk about in the tip 798.

Cover photo is courtesy of Wikimedia licensed under the Creative Commons Attribution 2.0 Generic license.

Leave a Reply

Your email address will not be published. Required fields are marked *