Guide on Service-to-Service (S2S) Authentication Flow for Business Central Integration

This guide will walk you through setting up Service-to-Service Authentication Flow (S2S) in Microsoft Business Central. This process involves creating a new Microsoft Business Central integration.

What is Service-to-Service integration?

Service-to-Service is the integration between any two platforms/services in a secure way that doesn’t require any human intervention once set up. It can function in an automated way. A lot of platforms have the functionality to integrate in such a way.

When to use service-to-service authentication for Business Central?

As mentioned above, service-to-service authentication should be used in cases where we need to integrate a 3rd party service with Business Central in a way that once that service is set up it can work automatically and securely. A third can exchange data with Business Central using service-to-service authentication in an automated way.

Prerequisites

To complete the Business Central integration, you will need the following two things

  • Administrative access to Business Central.
  • Administrative access to Azure Portal Account that has an active subscription.

Steps to Set Up Service-to-Service (S2S) Authentication Flow

  1. Register a Microsoft Entra application in the Azure Portal Account

    1. To begin the API integration process, Sign in to the Azure portal and register an application for Business Central in the Microsoft Entra tenant. Make sure you log in to the default directory.
      A screenshot of the Azure portal homepage showcases options for a free trial, Microsoft Entra ID, and student benefits, along with a navigation bar on top illustrating Service-to-Service (S2S) Authentication capabilities.
    2. Register the application for custom integration
      Screenshot of a Microsoft Entra Gallery page featuring a form to create a new application with Service-to-Service (S2S) Authentication. The form fields include the app's name and type, while options for various cloud platforms are conveniently displayed on the left.
      A webpage featuring the "Register an application" form for Business Central in Microsoft Entra, emphasizing fields for application information, supported account types, and Service-to-Service (S2S) Authentication options.
    3. Once registered, an overview of the new application will be displayed in the portal.
    4. Copy the Application (client) ID and Directory (tenant) ID of the registered application. You’ll need this later. You can get this value from the Overview page.
      Screenshot of Azure portal displaying application and directory IDs under "Essentials," with highlighted fields for Service-to-Service (S2S) Authentication essentials.
    5. Select Certificates & secrets > New client secret to generate a secret key for the API integration.
    6. Add a description, select a duration, and select Add.
      Screenshot of an Azure portal demonstrating Service-to-Service (S2S) Authentication: the creation of a client secret is shown. The Certificates & Secrets tab is open with details filled, and the "Add" button is highlighted for quick access.
    7. It will generate values. Copy the secret’s value to use it later.
      A screenshot of a client secrets management interface highlights "Entra Demo," crucial for Service-to-Service (S2S) Authentication, with an expiration date of 11/04/2024. The value and secret ID remain obscured. Satva Solutions logo is prominently visible, ensuring secure transactions.
    8. Add API permissions by selecting: API permissions > Add a permission > Microsoft APIs > Dynamics 365 Business Central.
      Screenshot of a permissions configuration page showcasing Azure services options, including Service-to-Service (S2S) Authentication and Dynamic 365 Business Central, with a Satva Solutions logo at the bottom right.
    9. Select the permissions for your custom integration and click on “Add Permissions”
      Screenshot of an API permissions request page highlighting options for delegated and application permissions in Dynamics 365 Business Central. Ideal for Service-to-Service (S2S) Authentication setups, the "Add permissions" button is conveniently located at the bottom.
    10. Grant the registered application permission for the directory.
      Screenshot of a permissions configuration interface showcasing Service-to-Service (S2S) Authentication, featuring a highlighted option for granting admin consent for the default directory. Various APIs are listed with their consent status marked as "Yes.
  2. Set up the Microsoft Entra application in the Business Central Account

      1. 2In the Business Central client, search for “Microsoft Entra applications” and open the page.
        Screenshot of Microsoft Dynamics 365 Business Central interface demonstrating Service-to-Service (S2S) Authentication with a search for "Microsoft data applications," showcasing results and the navigation menu.
      2. Create a New Microsoft Entra Application Card.
      3. In the Client ID field, enter the Application (Client) ID for the registered application in Microsoft Entra ID from step 1.
      4. Fill in the Description and Status to Enabled.
      5. Assign Admin permissions.
        Screenshot of Microsoft Entra Business Central interface displaying general settings with highlighted entries and user permission sets, including an administrator role with system permission scope, seamlessly integrating Service-to-Service (S2S) Authentication for enhanced security.
      6. https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/automation-apis-using-s2s-authentication

    Also Read: Guide to Integration with Microsoft Dynamics 365 Business Central for System Integrator

  3. Calling an API in Postman

    1. To verify the API integration, generate an access token using the following values
      • Application (client) ID (Microsoft Entra)
      • Directory (tenant) Id (from Business Central)
      • Client Secret Value (Microsoft Entra)
      Screenshot of a web interface demonstrating Service-to-Service (S2S) Authentication with a POST request. Parameters like client ID, secret, and scope are neatly arranged in a table. The JSON response displays an access token and its expiration time, highlighting secure data exchange.
    2. Use this access token to call Business Central APIs, such as retrieving the account’s companies, to ensure the Business Central integration functions correctly.
      Set up an API request for the 'Companies' endpoint in Postman using Service-to-Service (S2S) Authentication with bearer token authorization.

Here’s the C# code to generate the access token and refresh token.



using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace BusinessCentral.Authentication
{
    internal class BusinessCentralIntegration
    {
        public string ClientId { get; set; }
        public string ClientSecret { get; set; }
        public string TenantId { get; set; }
        public string Scope { get; set; }
        public string LoginUrl { get; set; }

    }

    internal class BusinessCentralToken
    {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }

        [JsonProperty("expires_in")]
        public string ExpiresAfterSeconds { get; set; }
    }

    internal class BusinessCentralAuthenticationHelper
    {
        private readonly BusinessCentralIntegration bcCredentials;
        private readonly string tokenEndPointUrl;
        private readonly HttpClient httpClient;

        public BusinessCentralAuthenticationHelper(BusinessCentralIntegration bcCredentials, HttpClient httpClient)
        {
            this.bcCredentials = bcCredentials;
            tokenEndPointUrl = $"{bcCredentials.LoginUrl}{bcCredentials.TenantId}/oauth2/v2.0/token";
            this.httpClient = httpClient;
        }

        public async Task<BusinessCentralToken> GetAccessToken()
        {
            var requestParams = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("grant_type", "client_credentials"),
                new KeyValuePair<string, string>("client_id", bcCredentials.ClientId),
                new KeyValuePair<string, string>("client_secret", bcCredentials.ClientSecret),
                new KeyValuePair<string, string>("scope", bcCredentials.Scope)
            };

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, tokenEndPointUrl)
            {
                Content = new FormUrlEncodedContent(requestParams)
            };

            var httpResponse = await httpClient.SendAsync(httpRequest);

            var responseJson = await httpResponse.Content.ReadAsStringAsync();
            if (!httpResponse.IsSuccessStatusCode)
            {
                throw new Exception($"Authentication failed for the following reason: {responseJson}");
            }

            BusinessCentralToken token = JsonConvert.DeserializeObject<BusinessCentralToken>(responseJson);

            if (token == null)
            {
                throw new Exception($"Authentication failed. Can't deserialize response: {responseJson}");
            }

            return token;
        }
    }
}

	

Ensure that the token is created and the API is called properly.

Download the source code of my application here, you need to replace the blank values in the configuration.

Article by

Chintan Prajapati

Chintan Prajapati, a seasoned computer engineer with over 20 years in the software industry, is the Founder and CEO of Satva Solutions. His expertise lies in Accounting & ERP Integrations, RPA, and developing technology solutions around leading ERP and accounting software, focusing on using Responsible AI and ML in fintech solutions. Chintan holds a BE in Computer Engineering and is a Microsoft Certified Professional, Microsoft Certified Technology Specialist, Certified Azure Solution Developer, Certified Intuit Developer, and Xero Developer.Throughout his career, Chintan has significantly impacted the accounting industry by consulting and delivering integrations and automation solutions that have saved thousands of man-hours. He aims to provide readers with insightful, practical advice on leveraging technology for business efficiency.Outside of his professional work, Chintan enjoys trekking and bird-watching. Guided by the philosophy, "Deliver the highest value to clients". Chintan continues to drive innovation and excellence in digital transformation strategies from his base in Ahmedabad, India.