Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Answered

Getting CRM service using OAuth authentication method

Posted on by 384

Hi Guys,

I have an Azure AD account and registered an app, selected Dynamics CRM permission to it in the Azure, added it to the application users and assigned it with an system administrator role.

After that, I tried to use the following code to get service, but it is failed. Is it because I am missing some other parameters in the connection string, such as ClientSecret or token or something else?

            string url = "https://XXX.crm.dynamics.com";
            string userName = ;
            string password = ;
            string appId= ;
            string redirectUri = ;

            string conn = $@"
            Url = {url};
            AuthType = OAuth;
            UserName = {userName};
            Password = {password};
            AppId = {appId};
            RedirectUri = {redirectUri};
            LoginPrompt=Never;";

            using (var svc = new CrmServiceClient(conn))
            {
                WhoAmIRequest request = new WhoAmIRequest();
                //
                WhoAmIResponse response = (WhoAmIResponse)svc.Execute(request);
                //
                Console.WriteLine("Your UserId is {0}", response.UserId);
                Console.WriteLine("Your Organization ID is {0}", response.OrganizationId);

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
            }

Thanks

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Getting CRM service using OAuth authentication method

    Hi,

    Can you please check LastCrmError property to see the detailed error which is available under 'svc'.

    Also, check IsReady property. If it is true then connection succedded else failed.

    Please mark my answer verified if i were helpful

  • Stone Huang Profile Picture
    Stone Huang 384 on at
    RE: Getting CRM service using OAuth authentication method

    It didn't report an error, but that's what I showed when I put my mouse over the ‘svc’.

    3107.Untitled.png

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Getting CRM service using OAuth authentication method

    Hi,

    What is the error you are getting when you use OAuth?

    Please mark my answer verified if i were helpful

  • Stone Huang Profile Picture
    Stone Huang 384 on at
    RE: Getting CRM service using OAuth authentication method

    I read the connection string provided in your repo. I also use these fields, but the values are different. I don't understand why not.

    I also registered an app, selected Dynamics CRM API permission to it in the Azure, added it to the application users and assigned it with an system administrator role. But ClientSecret is fine, OAuth is not working.

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Getting CRM service using OAuth authentication method

    Hi,

    Only AuthType=Office365 is impacted. AuthType with OAuth and ClientSecret would work fine.

    See below article.

    docs.microsoft.com/.../authenticate-office365-deprecation

    I have also created console application with OAuth. If you want to give it try you can clone my repo and replace connectionstring with yours.

    github.com/.../WorkWithCsharp

    Please mark my answer verified if i were helpful

  • Stone Huang Profile Picture
    Stone Huang 384 on at
    RE: Getting CRM service using OAuth authentication method

    Hi Bipin,

    Thank you for your reply, I tried this way you gave, it can work well.

    The reason why I intend to change the authentication method from WS-Trust to OAuth, is that WS-Trust will be abandoned in the near future. I'm not sure if ClientSecret is the same as WS-Trust. If not, that would be great.

    Thanks,

    Dejun

  • Suggested answer
    TNS Profile Picture
    TNS 1,195 on at
    RE: Getting CRM service using OAuth authentication method

    Hi,

    There are two ways for authenticating one is "User Based Authentication" and second "S2S Authentication".

    Here you are giving username and password so try below code :

    using Microsoft.IdentityModel.Clients.ActiveDirectory;

    using Newtonsoft.Json.Linq;

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Net.Http;

    using System.Net.Http.Headers;

    using System.Text;

    using System.Threading.Tasks;

    namespace Authentication

    {

       class Program

       {

           private static string serviceUrl = "provide the crm url";

           private static string clientId = "********************";

          private static string userName = "****************";

           private static string password = "*********";

           static void Main(string[] args)

           {

               HttpMessageHandler messageHandler;

               try

               {

                   messageHandler = new OAuthMessageHandler(serviceUrl, clientId, userName, password,

                                    new HttpClientHandler());

                   //Create an HTTP client to send a request message to the CRM Web service.  

                   using (HttpClient client = new HttpClient(messageHandler))

                   {

                       //Specify the Web API address of the service and the period of time each request  

                       // has to execute.  

                       client.BaseAddress = new Uri(serviceUrl);

                       client.Timeout = new TimeSpan(0, 2, 0);  //2 minutes

                       client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");

                       client.DefaultRequestHeaders.Add("OData-Version", "4.0");

                       client.DefaultRequestHeaders.Accept.Add(

                           new MediaTypeWithQualityHeaderValue("application/json"));

                       //Send the WhoAmI request to the Web API using a GET request.  

                       var response = client.GetAsync("https://********.api.crm8.dynamics.com/api/data/v9.1/WhoAmI",

                               HttpCompletionOption.ResponseHeadersRead).Result;

                       if (response.IsSuccessStatusCode)

                       {

                           //Get the response content and parse it.  

                           JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);

                           Guid userId = (Guid)body["UserId"];

                           Console.WriteLine("Your system user ID is: {0}", userId);

                       }

                       else

                       {

                           throw new Exception(response.ReasonPhrase);

                       }

                   }

               }

               catch (Exception ex)

               {

                   DisplayException(ex);

               }

           }

           /// <summary> Displays exception information to the console. </summary>  

           /// <param name="ex">The exception to output</param>  

           private static void DisplayException(Exception ex)

           {

               Console.WriteLine("The application terminated with an error.");

               Console.WriteLine(ex.Message);

               while (ex.InnerException != null)

               {

                   Console.WriteLine("\t* {0}", ex.InnerException.Message);

                   ex = ex.InnerException;

               }

           }

       }

       class OAuthMessageHandler : DelegatingHandler

       {

           private UserPasswordCredential _credential;

           private AuthenticationContext _authContext = new AuthenticationContext("login.microsoftonline.com/common", false);

           private string _clientId;

           private string _serviceUrl;

           public OAuthMessageHandler(string serviceUrl, string clientId, string userName, string password,

                   HttpMessageHandler innerHandler)

               : base(innerHandler)

           {

               _credential = new UserPasswordCredential(userName, password);

               _clientId = clientId;

               _serviceUrl = serviceUrl;

           }

           protected override async Task<HttpResponseMessage> SendAsync(

                    HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)

           {

               try

               {

                   AuthenticationResult result = null;

                   result = await _authContext.AcquireTokenAsync(_serviceUrl, _clientId, _credential);

                   request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

                   //  new AuthenticationHeaderValue("Bearer", _authContext.(_serviceUrl, _clientId, _credential).AccessToken);

                   return await base.SendAsync(request, cancellationToken);

               }

               catch (Exception ex)

               {

                   throw ex;

               }

           }

       }

    }

    Please Mark by answer verified if it is helpful.

  • Verified answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Getting CRM service using OAuth authentication method

    Hi,

    What is the error you are getting?

    Can you try below connectionstring instead of using OAuth and check if it works.

    <add name="MyCDSServer"

     connectionString="

     AuthType=ClientSecret;

     url=contosotest.crm.dynamics.com;

     ClientId={AppId};

     ClientSecret={ClientSecret}"

     />

    Here only Client ID and Client Secret is required. You will have to add secret in your Azure AD App registration.

    Also, make sure you have provided CRM access under API  Connection in Azure AD App registration.

    Please mark my answer verified if i were helpful

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,269 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,198 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans