How to – Connect to Dynamics 365 Web API using OAuth 2.0 – Client Credentials


For quick reference – https://nishantrana.me/2021/01/06/sample-code-dynamics-365-web-api-organization-service/

In the last post we learned about connecting to Dynamics 365 Web API using Resource Owner Password Credential (ROPC), here we’d be covering the Client Credentials grant.

Check other posts on OAuth 2.0 and Dynamics 365 Web API

OAuth 2.0 with Dynamics 365 CE Web API

Client Credentials grant is designed for the client applications who are the resource owner and when basically there are no users involved, a batch (cron) job or a service using Web API, running in the background, on the server is one such example.

Sample console app to connect to CDS using AuthType – OAuth https://nishantrana.me/2020/11/09/sample-code-to-connect-to-cds-dynamics-365-ce-using-oauth/

Here we will not be using the authorization endpoint, and the client application will be sending its own credential, instead of impersonating a user, directly to the token endpoint. The benefit compared to basic authentication or API keys is that credentials are not being sent with every request, it is only sent while requesting the access tokens along with all the other benefits of using access token – stateless, fine-grained access control, access token lifetime etc.

Let us see an example of using the Client Credentials grant in our console application. Along with the Client Id that we got when we registered our client application in the Azure Active Directory, we would need the Client Secret.

Follow the below steps to generate the Client Secret

Login to Azure Admin Portal

https://portal.azure.com

Select the application registered and click on Certificates & secrets option


Click on New client secret button to generate the client secret. Copy the generated client secret. Select the expiry as per the need.

Copy the secret generated and save it, as it won’t be available later when we are navigating here.

Also, we can get the Authentication Token Endpoint, for that navigate to Overview à Endpoints

And copy the OAuth 2.0 token endpoint.

Next step is to create the Application User within Dynamics 365 CE corresponding to the client application.

Login to Dynamics 365 CE, Settings à Security à Users àset View as Application Users and click on New button

Set Application Id as the Client Id of the Application registered and specify other mandatory values and save the record.

Assign appropriate security role to the new application user added.

Other Sample Code –https://nishantrana.me/2021/01/06/sample-code-dynamics-365-web-api-organization-service/

Sample C# Code à


static void Main(string[] args)
{
// Dynamics CRM Online Instance URL
string resource = "https://bankfabdemo.crm.dynamics.com";

// client id and client secret of the application
ClientCredential clientCrendential = new ClientCredential("eb17e844-adfc-4757-ba6d-5384108e184a",
"p.eS+MI9cXkO_gQ02_lMlUXVSVCujyU0");

// Authenticate the registered application with Azure Active Directory.
AuthenticationContext authContext =
new AuthenticationContext("https://login.microsoftonline.com/bd88124a-ddca-4a9e-bd25-f11bdefb3f18/oauth2/v2.0/token");

AuthenticationResult authResult = authContext.AcquireToken(resource, clientCrendential);
var accessToken = authResult.AccessToken;

// use HttpClient to call the Web API
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

httpClient.BaseAddress = new Uri("https://bankfabdemo.crm.dynamics.com/api/data/v9.0/");

var response = httpClient.GetAsync("WhoAmI").Result;
if (response.IsSuccessStatusCode)
{
var userDetails = response.Content.ReadAsStringAsync().Result;
}

}

Within Fiddler à

Within Postman à

Sample Code – Dynamics 365 Web API / Organization Service

Hope it helps..

https://docs.microsoft.com/en-us/powerapps/developer/data-platform/xrm-tooling/use-connection-strings-xrm-tooling-connect#connection-string-examples

Below is the example using CrmServiceClient – replace client id, client secret and the URL – 

 string ConnectionString = "AuthType = ClientSecret; " +
                   "ClientId=ad7a1cc4-838b-4270-9c11-29eb1686e203; " +
                   "ClientSecret=m7.H2Di~vizo.jZ0odh-C-85qg70QPfnsI; " +
                   "Url = https://[org].crm.dynamics.com/;";
      
     

            CrmServiceClient svc = new CrmServiceClient(ConnectionString);
            
            if (svc.IsReady)
            {
               // perform the logic 
                   
            }
Advertisements
Advertisements

Author: Nishant Rana

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

9 thoughts on “How to – Connect to Dynamics 365 Web API using OAuth 2.0 – Client Credentials”

  1. Is it necessary to Have an Azure Account to register an app and get the api key and secret key?
    I have a dynamic crm 2016 server joind to local active directory.

    Liked by 1 person

Please share your thoughts

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

Power Spark

Power Spark By Shrangarika

Van Carl Nguyen

Exploration of Power Platform

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog of Paul Andrew

Sponsored by Cloud Formations Ltd

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Dynamics 365 Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM