Hello everybody,
I am going to call CRM(online) Web API from my public web site written in ASP .Net MVC. Site visitor can not enter Azure AD credentials and I can not use Microsoft.IdentityModel.Clients.ActiveDirectory library.
So, I started following steps described in this post: http://jopx.blogspot.cz/2017/06/using-postman-and-dynamics-365-web-api.html.
I receive token from Azure AD on Postman tool and I can request CRM Web API using this access_token.
But I can't receive a token from Azure AD in web site code. I receive error: (401) Unauthorized.
var tokenRequestUrl = string.Format(@"login.microsoftonline.com{0}/oauth2/token", azureTenantGuid); // Connect to the authentication server var request = (HttpWebRequest)WebRequest.Create(tokenRequestUrl); request.Method = "POST"; // Write our request to the request body using (var reqStream = await request.GetRequestStreamAsync()) { var postData = string.Format(@"client_id={0}&resource={1}&username={2}&password={3}&grant_type=password&client_secret={4}", clientId, crmUrl, userName, password, clientSecret); var postBytes = new ASCIIEncoding().GetBytes(postData); reqStream.Write(postBytes, 0, postBytes.Length); reqStream.Close(); } // Call the authentication server and parse out the response using (var response = (HttpWebResponse)request.GetResponse()) { var dataStream = response.GetResponseStream(); if (dataStream != null) { var reader = new StreamReader(dataStream); var json = reader.ReadToEnd(); ... } }
Is it possible to call from Web site? What is wrong in this code? Or do I need to make some settings on my local dev environment?
*This post is locked for comments
Hi Baur Taishmanov,
I have same problem. Can you share for me how to get Authentication from Azure, then use token to connect to CRM Web API?
Thanks so much,
Hello James,
Now I can call CRM(online) Web API using "Web API Helper Code". It also goes through Azure (Authentication.DiscoverAuthority, then Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext->AcquireToken(,,,)) and after that uses the token to connect to CRM.
James, thanks a lot for help and for recommendation to use non-interactive user!
Why are you going through Azure and trying to use a token there to connect to CRM. Here is a link that shows the basic setup of a CRM ASP.NET web app.
[View:https://msdn.microsoft.com/en-us/library/mt770386.aspx:750:50]
Here is a link that explains the connection string setup:
[View:https://msdn.microsoft.com/en-us/library/mt608573.aspx:750:50]
Unless I am missing something in your specific use case (i.e. what you are trying to accomplish, example contact us form creates lead in CRM...). I would recommend setting up a non-interactive user with a non-expiring password in CRM and use that account for the connection. If you are trying to setup a customer portal, then I would recommend using CRM Portals.
Mohamed Amine Mahmoudi
83
Super User 2025 Season 1
Community Member
54
Victor Onyebuchi
6