To query ce from outside ce using webapi, follow below steps:-
Prerequisites :-
- Azure ad application with secret generated (Azure Subscription should be with same Office 365 account as of your D365 instance-you can login to azure using your ce trail instance credentials) (Ref ms docs)
2. Application user created in ce with same application id
Once you have these prerequisites, below code will give you a Bearer token which can be used to query ce:
using Microsoft.IdentityModel.Clients.ActiveDirectory; using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace ConnectCRMUsingadapp_ClientCredentialGrant { class Program { private static readonly string API_URL = "https://<replacewithyoururl>.api.crm8.dynamics.com/api/data/v9.1/"; private static readonly string CLIENT_ID = "<ADAppClientId>"; private static readonly string CLIENT_SECRET = "<ADAppClientSecret>"; static void Main(string[] args) { var execute = Task.Run(async () => await Auth()); Task.WaitAll(execute); } public static async Task Auth() { // use below lines for old version (3.13.5) of adal library // AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync( // new Uri(API_URL)).Result; //Use below lines for latest version of adal library AuthenticationParameters ap = AuthenticationParameters.CreateFromUrlAsync( new Uri(API_URL)).Result; //for latest version of adal // use below lines for old version (3.13.5) of adal library //AuthenticationContext authContext = new AuthenticationContext(ap.Authority); //Use below lines for latest version of adal library AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/yourazuretenantid"); var clinetCredential = new ClientCredential(CLIENT_ID, CLIENT_SECRET); var token = authContext.AcquireTokenAsync(ap.Resource, clinetCredential).Result.AccessToken; using (HttpClient httpClient = new HttpClient()) { httpClient.Timeout = new TimeSpan(0, 2, 0); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); HttpResponseMessage response = await httpClient.GetAsync(API_URL + "/contacts?$top=1"); } } } }
Download solution from github
hey thanks it helped me
LikeLike
I’m glad it helped you.
LikeLike