Skip to main content

Notifications

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 13
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!
  • Suggested answer
    Dharmendra_Chavda Profile Picture
    Dharmendra_Chavda 260 on at
    Issue Retrieving Bearer Tokens for Business Central API Access in a C# Method
    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.
  • gdrenteria Profile Picture
    gdrenteria 12,290 Most Valuable Professional on at
    Issue Retrieving Bearer Tokens for Business Central API Access in a C# Method
    Hi Have you tried configuring the application in the admin center?
    Best
    GR
  • Suggested answer
    YUN ZHU Profile Picture
    YUN ZHU 74,036 Super User 2024 Season 2 on at
    Issue Retrieving Bearer Tokens for Business Central API Access in a C# Method
    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
     
     

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

News and Announcements

Announcing Category Subscriptions!

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Verified Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,359 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,370 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans