RE: Discovery web API in CRM online return error 401 - Unauthorized
Hi Ajyendra,
Main:
static void Main(string[] args)
{
try
{
String token = Authenticate().Result.AccessToken;
Task.WaitAll(Task.Run(async () => await GetInstances(token)));
}
catch (Exception e)
{
Console.WriteLine("Oh..an error occured..:\n " e);
}
}
Function to acquire token:
private static async Task Authenticate()
{
string userName = "";
string password = "";
string clientId = "";
string adminUrl = "https://admin.services.crm5.dynamics.com/";
var credentials = new UserPasswordCredential(userName, password);
var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/common/");
var result = await authenticationContext.AcquireTokenAsync(adminUrl, clientId, credentials);
return result;
}
Test for getting instances information:
private static async Task GetInstances(String token)
{
var httpClient = new HttpClient
{
BaseAddress = new Uri(Resource),
Timeout = new TimeSpan(0, 2, 0)
};
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var retrieveResponse =
await httpClient.GetAsync("/api/v1.2/instances");
if (retrieveResponse.IsSuccessStatusCode)
{
var jRetrieveResponse =
retrieveResponse.Content.ReadAsStringAsync().Result;
Console.WriteLine("Your instances retrieved from Office 365 tenant: \n{0}", jRetrieveResponse);
//var result = JArray.Parse(jRetrieveResponse);
//foreach (var data in result)
// Console.WriteLine("Id: " data["Id"] "\nUnique Name: " data["UniqueName"] "\n");
}
else
{
Console.WriteLine("The request failed with a status of '{0}'",
retrieveResponse.ReasonPhrase);
}
}
Regards,
Clofly