web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Small and medium business | Business Central, N...
Suggested Answer

Business Central 365 c# Oauth implementation

(0) ShareShare
ReportReport
Posted on by 130

Hi,

I am trying to implement Oauth logic for Business Central 365 via this code

private const string ClientId = "XXXXXXXXXX";
private const string ClientSecret = "XXXXXXXXXXX";
private const string AadTenantId = "XXXXXXXXXXX";
private const string Authority = "">login.microsoftonline.com/.../token"; // I do not know why, but dynamics forum does not allow me to write this here : // https ://login.microsoftonline.com/{AadTenantId}/oauth2/v2.0/token


private const string BCEnvironmentName = "XXXXXXXX";
private const string BCCompanyId = "XXXXXXXXXXX";

private const string BCBaseUrl = "">api.businesscentral.dynamics.com/.../companies({BCCompanyId}))";  // I do not know why, but dynamics forum does not allow me to write this here : https ://api.businesscentral.dynamics.com/v2.0/{BCEnvironmentName}/api/v2.0/companies({BCCompanyId})
private static AuthenticationResult AuthResult = null;

static void Main(string[] args)
{
string customers = CallBusinessCentralAPI(BCEnvironmentName, BCCompanyId, "customers").Result;
}

static async Task<AuthenticationResult> GetAccessToken(string aadTenantId)
{
Uri uri = new Uri(Authority.Replace("{AadTenantId}", aadTenantId));
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithClientSecret(ClientSecret)
.WithAuthority(uri)
.Build();
string[] scopes = new string[] { @"">api.businesscentral.dynamics.com/.default" }; // I do not know why, but dynamics forum does not allow me to write this here : https: //api.businesscentral.dynamics.com/.default
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Token acquired");
Console.ResetColor();
}
catch (MsalServiceException ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Error occurred while retrieving access token");
Console.WriteLine($"{ex.ErrorCode} {ex.Message}");
Console.ResetColor();
}
return result;
}
static async Task<string> CallBusinessCentralAPI(string bcEnvironmentName, string bcCompanyId, string resource)
{
string result = string.Empty;
if ((AuthResult == null) || (AuthResult.ExpiresOn < DateTime.Now))
{
AuthResult = await GetAccessToken(AadTenantId);
}
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthResult.AccessToken);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
resource = "purchaseInvoices";
Uri uri = new Uri(GetBCAPIUrl(bcEnvironmentName, bcCompanyId, resource));
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Call to Business Central API failed: {response.StatusCode} {response.ReasonPhrase}");
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Content: {content}");
Console.ResetColor();
}
}
return result;
}
private static string GetBCAPIUrl(string bcEnvironmentName, string bcCompanyId, string resource)
{
return BCBaseUrl.Replace("{BCEnvironmentName}", bcEnvironmentName).Replace("{BCCompanyId}", bcCompanyId) + "/" + resource;
}

The token is successfully generated, so there is anything wrong that I have done during configuration at Azure Active Directory

The error that I receive  during GET request is 401 Error

4035.pastedimage1668554390885v1.png

I followed instructions according to official documentation how to form URL - learn.microsoft.com/.../endpoints-apis-for-dynamics

6403.pastedimage1668554444434v2.png

But it did not help

That is how I am trying to from URl currently

3487.pastedimage1668554513429v3.png

What is wrong with my code ?

Thanks in advance

Kindest regards

I have the same question (0)
  • André Arnaud de Calavon Profile Picture
    300,911 Super User 2025 Season 2 on at

    Moved to the Dynamics 365 Business Central forum.

  • Suggested answer
    YUN ZHU Profile Picture
    95,329 Super User 2025 Season 2 on at

    Hi, Erik has a video about this that I hope will give you some help.

    Site-2-Site OAuth Authentication - From Scratch with C# and Business Central

    https://www.youtube.com/watch?v=eALHYuanfUQ

    pastedimage1668576631958v1.png

    Thanks.

    ZHU

  • Dynamics Questions Profile Picture
    130 on at

    Hi yzhums 

    Thanks for the response.

    I watched this video before creating this topic at Dynamics forum and have asked question concerning URl formation 

    Eric responded me with the following reference that I provided in description

    pastedimage1668613122300v1.png

    Unfortunately URL formation explanation is omitted in the video and in reference it is not clear where get <environment name> and <user domain name> parameters, I still do not know what are they exactly 

    So everything remains same as I explained it in question description 

  • Suggested answer
    YUN ZHU Profile Picture
    95,329 Super User 2025 Season 2 on at

    Hi, hope the following helps.

    <environment name>: 

    pastedimage1668646287453v1.png

    <user domain name>: Tenant id or Domain name

    pastedimage1668646318249v2.png

    In your environment, you will see tenant id and environment name. (Multiple environments)

    pastedimage1668646394333v3.png

    Hope this helps.

    Thanks.

    ZHU

  • Dynamics Questions Profile Picture
    130 on at

    Hi yzhums 

    Thank you very much for help with my task

    I followed your instructions. I tried these environment names 

    pastedimage1668710501778v1.png

    and tried Tenant id and Domain name in my request

    Unfortunately, the result remains the same with error : "Bad request"

    pastedimage1668710648994v2.png

    The rest of the code is same that I provided, it is same as Eric provided un his tutorial, token is generated successfully, but something wrong with this URL

  • Suggested answer
    YUN ZHU Profile Picture
    95,329 Super User 2025 Season 2 on at

    Hi, This is kind of weird, I did a quick test in Postman and below is my URL, it looks the same as yours.

    api.businesscentral.dynamics.com/.../customers

    pastedimage1668727815565v1.png

    pastedimage1668727823646v2.png

    Is it possible that you have not given enough permissions in Azure Active Directory Application Card?

    pastedimage1668727942250v3.png

    Hope this helps.

    Thanks.

    ZHU

  • Dynamics Questions Profile Picture
    130 on at

    Hi yzhums 

    Thanks for the provided description

    I will check it and provide an update 

  • Dynamics Questions Profile Picture
    130 on at

    Hi ZHU YUN

    I have done what you suggested previously

    pastedimage1669591593005v1.png

    Required rights are granted, but unfortunately result remains same

    pastedimage1669591692795v2.png

  • Suggested answer
    YUN ZHU Profile Picture
    95,329 Super User 2025 Season 2 on at

    Emmm, I suspect now that this may be an issue with the OAuth setup.

    Hope you can check the settings in Azure Portal again.

    More details: https://yzhums.com/20690/

    Hope this helps.

    Thanks.

    ZHU

  • Suggested answer
    DAnny3211 Profile Picture
    11,397 on at

    CIao

    first replicate everything with postman and make sure it works

    danieleincalza.blogspot.com/.../business-central-bye-bye-basic.html

    DAniele

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Small and medium business | Business Central, NAV, RMS

#1
OussamaSabbouh Profile Picture

OussamaSabbouh 3,229

#2
Jainam M. Kothari Profile Picture

Jainam M. Kothari 1,867 Super User 2025 Season 2

#3
YUN ZHU Profile Picture

YUN ZHU 1,153 Super User 2025 Season 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans