Hi ,
First thing,
I have registered my website to azure directory AD.
Now I am not able to find code to work.
I have website project, created webapi project.
Now, how to work on Authentication stuff, I need guidance to proceed further?(which assemblies to add, how to start the project)
Help please.
Thanks & Regards,
Abhinav
*This post is locked for comments
Can we get same token id using javascript ?
Hi Michel - I've tried to run the code listed here and for the most part it works. I notice that when I have "authenticated" to my target CRM, I am doing so under my own windows account. I get a token back and everything "looks" good but when I go to query the service I get back an unauthorized exception because it thinks I am running under this other account.
Oddly enough, when I run this same code via a Console app (the above is done using a Web API app) it works fine with no errors and I'm able to query the system no problem.
If I try to use the following url for authorization - login.windows.net/{0}/oauth2/authorize - this breaks immediately saying I'm trying to log in as this user (but again this is simply my development user and I'm only passing in the client id at this point in time).
Is there something I am missing here?
Any insight you can provide would be greatly appreciated - thank you.
Hi Abhinab,
Sorry for late reply.
You can go to your dynamics CRM --> Settings -->Customization --> Developer resource .
You can find over there the WEB API url.
Hope this helps.
What is that apiURL? what should i put?
awaiting your response.
Thansks
Hi Goutam,Sir
where can i get appurl?
I have created webproject published to azure.
registered to Azure AD
redirect urrl is the one i published to azure e.g: customer.azurewebsites.net
even getting PlatformParameters issue. could not find assembly name or namespace error.
Please explain me in steps.
so i can make it work.
Let me know the steps to execute it.
Hi Abhinav,
Yes you can create new CS file for authentication prpose.
Thank you so much.
So we dont need to create web api project for authentication stuff.
i can use this code in webapplication project creating new cs file?
Hi Abhinav,
Here is the sample code to get token.
using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Discovery; using Microsoft.Xrm.Tooling.Connector; using System; using System.Collections.Generic; using System.Configuration; using System.IdentityModel.Tokens; using System.Linq; using System.Net; using System.Net.Http; using System.ServiceModel.Description; using System.Text; using System.Threading.Tasks; using Microsoft.IdentityModel.Clients.ActiveDirectory; using System.Net.Http.Headers; using static System.Console; namespace OnlineLogin { class ConnectAzure { static Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext; /// <summary> /// Holds the actual authentication token once after successful authentication /// </summary> static AuthenticationResult authToken; /// <summary> /// This is the API data url which we will be using to automatically get the /// a) Resource URL - nothing but the CRM url /// b) Authority URL - the Microsoft Azure URL related to our organization on to which we actually authenticate against /// </summary> static string apiUrl = "xxxxxx.api.crm8.dynamics.com/.../data"; /// <summary> /// Client ID or Application ID of the App registration in Azure /// </summary> static string clientId = "11a95164-eae4-4ab4-8d9b-ac32d885c7cd"; /// <summary> /// The Redirect URL which we defined during the App Registration /// </summary> static string redirectUrl = "ms-console-app://consoleapp"; internal static async void GetToken() { try { // Get the Resource Url & Authority Url using the Api method. This is the best way to get authority URL // for any Azure service api. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(apiUrl)).Result; string resourceUrl = ap.Resource; string authorityUrl = ap.Authority; //Generate the Authority context .. For the sake of simplicity for the post, I haven't splitted these // in to multiple methods. Ideally, you would want to use some sort of design pattern to generate the context and store // till the end of the program. authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authorityUrl, false); try { //Check if we can get the authentication token w/o prompting for credentials. //With this system will try to get the token from the cache if there is any, if it is not there then will throw error authToken = await authContext.AcquireTokenAsync(resourceUrl, clientId, new Uri(redirectUrl), new PlatformParameters(PromptBehavior.Never)); } catch (AdalException e) { if (e.ErrorCode == "user_interaction_required") { // We are here means, there is no cached token, So get it from the service. // You should see a prompt for User Id & Password at this place. authToken = await authContext.AcquireTokenAsync(resourceUrl, clientId, new Uri(redirectUrl), new PlatformParameters(PromptBehavior.Auto)); } else { throw; } } WriteLine("Got the authentication token, Getting data from Webapi !!"); GetData(authToken.AccessToken); } catch (Exception ex) { WriteLine($"Some thing unexpected happened here, Please see the exception details : {ex.ToString()}"); } } internal static async void GetData(string token) { using (HttpClient httpClient = new HttpClient()) { httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes time out period. // Pass the Bearer token as part of request headers. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var data = await httpClient.GetAsync("xxxxxx.api.crm8.dynamics.com/.../accounts$select=name"); if (data.StatusCode == System.Net.HttpStatusCode.OK) { // If the status code is success... then print the api output. WriteLine(await data.Content.ReadAsStringAsync()); } else { // Failed .. ??? WriteLine($"Some thing went wrong with the data retrieval. Error code : {data.StatusCode} "); } ReadLine(); } } } }
Hope this helps
Hello,
In C# you can use the ADAL libraries version 2 (not version 3!) to connect.
They are available via this NuGet package:
https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/2.28.4
Here's an introduction to using ADAL to connect to Dynamics 365:
The jist of it is this piece of code:
string resource = "organizationname.crm.dynamics.com"; // TODO Substitute your app registration values that can be obtained after you // register the app in Active Directory on the Microsoft Azure portal. string clientId = "e5cf0024-a66a-4f16-85ce-99ba97a24bb2"; string redirectUrl = "localhost/SdkSample"; // Authenticate the registered application with Azure Active Directory. AuthenticationContext authContext = new AuthenticationContext("login.windows.net/common", false); AuthenticationResult result = authContext.AcquireToken(resource, clientId, new Uri(redirectUrl)); using (HttpClient httpClient = new HttpClient()) { httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); // TODO: Call WebApi }
Hope this helps you get started. If you have any other questions, please let me know!
If you found my answer helpful, please help the community by marking it as verified :-)
Stay up to date on forum activity by subscribing. You can also customize your in-app and email Notification settings across all subscriptions.
André Arnaud de Cal... 291,253 Super User 2024 Season 2
Martin Dráb 230,188 Most Valuable Professional
nmaenpaa 101,156