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

Issue Retrieving Bearer Tokens for Business Central API Access in a C# Method

(1) ShareShare
ReportReport
Posted on by 35
Hello,
 
I am attempting to access the Business Central API from a C# application. The program successfully connects to BC and gets a token, but the request using that token fails with StatusCode: 401, ReasonPhrase: 'Unauthorized'.
 
This process works fine in Postman, and if I copy the token from the working Postman and paste it into the C# code, the API request works fine. The token retrieved from BC appears to be much shorter than the one that is obtained in Postman.
 
I'm guessing it's something simple I am missing, but I can find what that might be.
 
Here is my code.
 
static async Task RunApiTest()
{
    try
    {
        string bearerToken = "";
        string ClientId = "(removed)";
        string ClientSecret = "(removed)";
        string TenantId = "(removed)";
        string tokenUrl = $"https://login.microsoftonline.com/{TenantId}/oauth2/v2.0/token";
        HttpClient client = new HttpClient();
        var content = new StringContent("grant_type=client_credentials" +
                                        "&scope=https://api.businesscentral.dynamics.com/.default" +
                                        "&client_id=" + HttpUtility.UrlEncode(ClientId) +
                                        "&client_secret=" + HttpUtility.UrlEncode(ClientSecret));
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
        var response = await client.PostAsync(tokenUrl, content);
        if (response.IsSuccessStatusCode)
        {
            var tokenContent = await response.Content.ReadAsStringAsync();
            var tokenResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenResponse>(tokenContent);
            bearerToken = tokenResponse.AccessToken;
            string apiUrl = $"https://api.businesscentral.dynamics.com/v2.0/(removed)/Sandbox/api/v2.0/companies((removed))/customers";
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + bearerToken);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var apiRespponse = await httpClient.GetAsync(apiUrl);
            if (apiRespponse.IsSuccessStatusCode)
            {
                string resultString = await httpClient.GetStringAsync(apiUrl);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
public class TokenResponse
{
    [Newtonsoft.Json.JsonProperty("access_token")]
    public string AccessToken { get; set; }
}
 
Thanks!
I have the same question (0)
  • Suggested answer
    YUN ZHU Profile Picture
    95,647 Super User 2025 Season 2 on at
    Hi, Sorry, I'm not sure. It seems to be the problem in this part. If it is written as fixed, can it pass authorization?
     
    Here is the Oauth test I did in Power Automate, hope it can give you some hints.
     
     
    Thanks.
    ZHU
     
     
  • Gerardo Rentería García Profile Picture
    25,225 Most Valuable Professional on at
    Hi Have you tried configuring the application in the admin center?
    Best
    GR
  • Suggested answer
    Chavda Dharmendra Profile Picture
    1,000 on at
    Hello,
     
    The below code is working fine for me.
     
    try this one.
     
    static async Task Main1(string[] args)
    {
        string ClientId = "(removed)";
        string ClientSecret = "(removed)";
        string TenantId = "(removed)";
        string URL = "https://login.microsoftonline.com/" + TenantId + "/oauth2/v2.0/token";
        HttpClient client = new HttpClient();
        var content = new StringContent("grant_type=client_credentials" +
                            "&scope=https://api.businesscentral.dynamics.com/.default" +
                            "&client_id=" + HttpUtility.UrlEncode(ClientId) +
                            "&client_secret=" + HttpUtility.UrlEncode(ClientSecret));
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
        var response = await client.PostAsync(URL, content);
        if (response.IsSuccessStatusCode)
        {
            JObject Result = JObject.Parse(await response.Content.ReadAsStringAsync());
            string BearerToken = Result["access_token"].ToString();
            //Token Generated
           // API CAll
            var client1 = new RestClient("https://api.businesscentral.dynamics.com/v2.0/TenantId/Sandbox/ODataV4/Company('CRONUS%20IN')/ItemCard('1896-S')");
            client1.Timeout = -1;
            var request = new RestRequest(Method.GET);
            request.AddHeader("Authorization", "Bearer " + BearerToken);
            IRestResponse response1 = client1.Execute(request);
            Console.WriteLine(response1.Content);
        }
        else
        {
            Console.WriteLine(response.Content);
        }
    }
     
    If it works then mark a verified answer.

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 2,577

#2
YUN ZHU Profile Picture

YUN ZHU 888 Super User 2025 Season 2

#3
Jainam M. Kothari Profile Picture

Jainam M. Kothari 778 Super User 2025 Season 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans