
I've been researching for days now on how to authenticate an office365 user licensed to use dyamics 365 crm to access the dynamics api.
I can successfully get a token using either a ClientCredential or a UserCredential, but when I try and access the API with the token, I get a 401.
Here's the code I'm using to try and access the API:
using (HttpClient httpClient = new HttpClient())
{
GetAuthorizationToken();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
httpClient.BaseAddress = new Uri("xxxxxxx.crm.dynamics.com/.../v8.1");
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minute timeout
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var req = httpClient.GetAsync("accounts").Result;
}
req always has a 401.
Here are the two methods I've used to get the token (AquireToken with cc and other with user credential).
AuthenticationResult result = null;
AuthenticationContext authContext;
// Authenticate the registered application with Azure Active Directory.
authContext = new AuthenticationContext(_authority);
ClientCredential cc = new ClientCredential(_clientId, _clientSecret);
//result = authContext.AcquireToken(_serverAddress, cc);
result = authContext.AcquireToken(_serverAddress, _clientId2, new UserCredential("user@domain.com", @"mypassword"));
if (!String.IsNullOrEmpty(result.AccessToken))
{
_accessToken = result.AccessToken;
_tokenExpiry = result.ExpiresOn;
}
I even tried an online adal js library, but get a similar result.
I've tried client id's from both a WebAPI application in Azure as well as a Native application. They both authenticate correctly, but I still get the 401 unauthorized.
Is there some configuration that needs to be done in CRM to access it? The user account I've tried to access CRM with is both an office365 admin and a dynamics crm admin.
*This post is locked for comments
I have the same question (0)My issue ended up being that I needed to use xxx.crm3.dynamics.com instead of just crm without the 3.
Also for those who may come across this in the future - using Client Credentials will get you an auth token, but it will still give you a 401 when accessing the api