C# Program to Call Web Services with OAuth 2.0 Authentication in BC

The following C# (C Sharp) program that I made will help to call web services or APIs in Business Central accessing by OAuth 2.0 authentication. Here I have called the “Char of Accounts” web service as an example.

using System.Web;
using Newtonsoft.Json.Linq;
namespace BCCloudOAuthWebService
{
    class Program
    {
        static string clientId="1bc2bcef-5052-4e4c-8d6b-363ef278bcbc";    // Application (client) ID
        static string secret="cuc8Q~C5FlJG5kg.vbROV-lpeqlDqa1ahuRXOais";  // Secret value
        static string tenantId="0224d299-271d-4ab6-8b5f-ff52b32ede8b";    // Directory (tenant) ID
        static string url="https://login.microsoftonline.com/"+tenantId+"/oauth2/v2.0/token";
        public static async Task Main(string []args){
            await sendRequest("https://api.businesscentral.dynamics.com/v2.0/"+tenantId+"/Production/ODataV4/Company('CRONUS%20USA%2C%20Inc.')/Chart_of_Accounts");
        }
        static async Task sendRequest(string requestApiUrl){
            string bearerToken=await getBearerAccessToken();
            if(bearerToken=="") return;
            HttpClient requestHttpClient=new HttpClient();
            requestHttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer "+bearerToken);
            var requestResponse=await requestHttpClient.GetAsync(requestApiUrl);                
            if(requestResponse.IsSuccessStatusCode)
                Console.WriteLine(await requestResponse.Content.ReadAsStringAsync());
            else
                Console.WriteLine("Error from sending request: "+requestResponse.StatusCode.ToString());
        }
        static async Task<string> getBearerAccessToken(){  
            HttpClient httpClient=new HttpClient();
            var content= new StringContent("grant_type=client_credentials&scope=https://api.businesscentral.dynamics.com/.default&client_id="
            +HttpUtility.UrlEncode<pre>(clientId)</pre>+"&client_secret="+HttpUtility.UrlEncode<pre>(secret)</pre>);
            content.Headers.ContentType=new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
            var response=await httpClient.PostAsync(url,content);
            if(response.IsSuccessStatusCode){
                JObject result=JObject.Parse(await response.Content.ReadAsStringAsync());
                return result["access_token"].ToString();
            }else{
                Console.WriteLine("Error from getting access token: "+response.StatusCode.ToString());
                return "";
            }
        }
    }
}
Code language: JavaScript (javascript)

Visit the previous guide about how to register Business Central application in Azure Portal.

Senior Solutions Architect - Microsoft Dynamics Navision / Microsoft Dynamics 365 Business Central and freelance developer. (The admin of NAVUSER)

Leave a Comment