I'm currently trying to create a Xamarin App in order to get some info from a Dynamics 365 online instance. The code that authenticate with AD and access the CRM api is deported in a NetStandard (v1.6) Library.
I use the following NuGets :
- Microsoft.IdentityModel.Clients.ActiveDirectory (3.13.9)
- NETStandard.Library (1.6.1)
I followed the following tutorial in order to link AD with my Dynamics instance : https://nishantrana.me/2016/11/13/register-a-dynamics-365-app-with-azure-active-directory/
Here is my ActiveDirectory helper :
public static class ADHelper
{
public async static Task<AuthenticationResult> GetAuthAsync(Uri uri, ClientCredential creditential)
{
AuthenticationParameters ap = await AuthenticationParameters.CreateFromResourceUrlAsync(uri);
String authorityUrl = ap.Authority;
String resourceUrl = ap.Resource;
AuthenticationResult result = null;
AuthenticationContext authContext = new AuthenticationContext(authorityUrl, false);
result = await authContext.AcquireTokenAsync(resourceUrl, creditential);
return result;
}
}
And my CRM API Client :
public class CRMClient
{
private AuthenticationResult Auth { get; set; }
private Uri baseUri { get; set; }
public CRMClient(Uri uri, ClientCredential creditential)
{
baseUri = uri;
Auth = ADHelper.GetAuthAsync(uri, creditential).Result;
}
public void getObject()
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Auth.AccessToken);
client.Timeout = new TimeSpan(0, 2, 0);
client.BaseAddress = baseUri;
HttpResponseMessage message = client.GetAsync("/accounts").Result;
String content = message.Content.ReadAsStringAsync().Result;
}
}
Parameters used for CRMClient Constructor :
- https://[my_crm_instance_Url]/api/data/v8.2/ => the data OData endpoint
- ClientCredential(AppId, AppKey) => as credential
Azure AD gives me a token back, but UserInfo, TenantId and idToken are all null
(This could be a part of the cause of my problem).
Currently, the returned content is the HTML office 365 login page instead of the data I wanted to get.
Could someone help me?
I create a full blog post here
http://phuocle.net/crm/dynamics-365-online-s2s-authentication-full-explain.aspx