Hi @Steve Morris , to get tokens and API responses using OAuth for external tenants, you need to use the tenant ID of the external tenant. The tenant ID is a unique identifier for the tenant, and it is different for each tenant.In your code, you are using the tenant_Id
variable to specify the tenant ID. To get the external tenant's company file, you need to replace the tenant_Id
variable with the external tenant's tenant ID.
The API endpoint for getting the company file is https://api.businesscentral.dynamics.com/v2.0/{tenant-id}/Production/api/v2.0/companies/
. You need to replace {tenant-id}
with the external tenant's tenant ID.
Here is an updated version of your code with the changes:
string accessToken = string.Empty;
using (HttpClient client = new HttpClient())
{
string tokenEndpoint = "https://login.microsoftonline.com/" + tenant_Id + "/oauth2/v2.0/token/";
var tokenRequestContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("client_id", client_Id),
new KeyValuePair<string, string>("client_secret", client_secret),
new KeyValuePair<string, string>("redirect_uri", redirectUri),
new KeyValuePair<string, string>("scope", "openid offline_access"),
});
HttpResponseMessage responseval = await client.PostAsync(tokenEndpoint, tokenRequestContent);
if (responseval.IsSuccessStatusCode)
{
string jsonResponse = await responseval.Content.ReadAsStringAsync();
dynamic json = JObject.Parse(jsonResponse);
accessToken = json.access_token != null ? json.access_token : string.Empty;
}
}
using (HttpClient client1 = new HttpClient())
{
string companiesEndpoint = "https://api.businesscentral.dynamics.com/v2.0/{external-tenant-id}/Production/api/v2.0/companies/";
string Access_Token = accessToken.ToString();
client1.DefaultRequestHeaders.Add("Authorization", "Bearer " + Access_Token);
HttpResponseMessage response1 = await client1.GetAsync(companiesEndpoint);
if (response1.IsSuccessStatusCode)
{
string jsonResponsevalue = await response1.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<dynamic>(jsonResponsevalue);
}
}
Replace {external-tenant-id}
with the external tenant's tenant ID.
Let me know if this works. If not please let me know and I can help you further!
If this answer helps you please mark "Accept Answer" so other users can reference it.
Thank you,
James