Calling Rapid Start Automation APIs using OAuth2.0 Authentication

 I saw that authentication for Business Central APIs were changing from Basic to OAuth2.0. So, I wanted to see how this impacted service to service calls to the APIs. This blog will focus on calling Business Central Online. For Business Central on-premise, you can still use Basic Authentication and web service keys.

Please review these Microsoft links before further reading this blog. 

https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/itpro-introduction-to-automation-apis

Getting Started Developing Connect Apps for Dynamics 365 Business Central - Business Central | Microsoft Docs

Since Microsoft’s initial announcement of deprecating basic authentication earlier in the year, it appears that service to service calls using OAuth2.0 can not only be used for Business Central Automation APIs, but they can also be used for standard APIs as well. We’ll discuss that a little, too.

Let’s Get Started

Create an App Registration

Get started by creating your App Registration in the Azure Active Directory.

You can find documentation from Microsoft here. You will be doing Task 1 in that documentation.

Use the Microsoft documentation at that link to create your app registration. Be sure to grab the client secret and save it in a safe place so you can use it in your application.

I would like to add that if you are using Postman online, add the API redirect url https://oauth.pstmn.io/v1/browser-callback to the list of redirect urls so you can authenticate with Postman online:

Rapid Start automation 1

Also, Microsoft provides OAuth 2.0 code examples in the in the Quickstart menu of the Register App Section. So, I like to add the API permissions pictured below to make sure I can use the Microsoft examples I like. For instance, I like to test with a Daemon application for .Net Core., and I like to have all the permissions listed below to support that along with my Business Central apps.

Rapid-Start-automation-2

Setup the App Registration in Business Central

Use the documentation from Microsoft here.  It’s the same link as the one above to setup your app registration, but it’s Task 2.

Some things to point out, you don’t have to grant consent here if it’s already been done in the Azure Active Directory when setting up your App Registration.

Also, be sure not to overlook the Permissions. You need to assign permissions to the Azure Active Directory Registration in Business Central. You do this right on the Azure Active Directory page, and you add them just like you would add them to a user, using User Group permission sets or individual permission sets. You can’t assign the SUPER permission. The system won’t allow you, so assign the permission sets the application needs to write and read from the system for the task it is performing.

Note the User Groups and User Permission Sets in the picture below. These fast tabs are where you can assign your permissions.

Rapid-Start-automation-3

Let’s Authenticate!

We’ll start learning how to authenticate with OAuth2.0 using an Automation API called configurationPackages. The url for the configurationPackages api is:

**Put the environment name you want to connect to where the above url says . Put the guid of the company you want to connect to where the url says .

Here’s an example where the environment name is Production and the company id is 277114a9-621d-ea11-bb2d-000d3a257ac9:
https://api.businesscentral.dynamics.com/v2.0/Production/api/microsoft/automation/v2.0/companies(277114a9-621d-ea11-bb2d-000d3a257ac9)/configurationPackages

https://api.businesscentral.dynamics.com/v2.0/yourenvironmentName/api/microsoft/automation/v2.0/companies(yourcompanyId)/configurationPackages.

(You can get Microsoft documentation for this automation apis and others at: https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/itpro-introduction-to-automation-apis)

Imagine someone exported a .rapidstart file from a Business Central environment (not an excel workbook, but a configuration file with the .rapidstart file extension) and needed you to import that file into another environment using the automation API. You would want to:

  1. Create the Configuration Package in the new environment if not already created.
  2. Upload the configuration .rapidstart file into the configuration package.
  3. Import the file into the configuration package. (This is actually a separate step from uploading the file. Uploading gets the system ready to use the file, but doesn’t import.)
  4. Apply the configuration package. Just like a user applying a configuration package in the Web Client, the automation API can apply the imported file and update the system.

The api calls to perform the steps above are:

  1. Create the configuration package: Post (You will use the Post method for this call) to url: https://api.businesscentral.dynamics.com/v2.0/yourenvironmentname/api/microsoft/automation/v2.0/companies(companyId)/configurationPackages

    The environment name is the name of the Business Central environment you are connecting to. For instance, Production, Sandbox, etc., whatever you named your environments when you set them up.

    The companyid is the “id” of the Business Central company you are writing to. It's found by using the Get method to call the following url: https://api.businesscentral.dynamics.com/v2.0/environmentname/api/microsoft/automation/v2.0/companies. After calling that api, finding the “id” in the json returned for the company you want to write to. (The header of the call to the companies api should contain the following: Authorization: Bearer {token} – the token is the token you retrieved from Business Central).

    The header of the call to the configurationpackages api should contain the following keys:
    Authorization: Bearer {token}
    Content-type: application/json
    The token referenced above is the token you retrieved from Business Central.
    And the json body for the configurationpackages api should at least contain the code node and its value:
    {
    "code":"TYPEYOURPACKAGECODE",
    }

    This post returns a json string that contains the “id” node containing the configuration package id you will use in the following api calls.

  2. Upload the configuration file: Patch (use the Patch method for this call) to url:
    https://api.businesscentral.dynamics.com/v2.0/yourenvironmentname/api/microsoft/automation/v2.0/companies(companyId)/configurationPackages(yourconfigpackageid)/file(‘TYPEYOURPACKAGECODE’)/content

    The TYPEYOURPACKAGECODE in the url above is the package code you chose to use to create the configuration package. The yourconfigpackageid is the id for the configuration package you are modifying.

    So an example url where the environment name is Production, the company id is 277114a9-621d-ea11-bb2d-000d3a257ac9, and the configuration package id is 477114a9-621d-ea11-bb2d-000d3a257ac6 would be:
    https://api.businesscentral.dynamics.com/v2.0/Production/api/microsoft/automation/v2.0/companies(277114a9-621d-ea11-bb2d-000d3a257ac9)/configurationPackages(477114a9-621d-ea11-bb2d-000d3a257ac6)


    The header keys for this call should contain:
                      Authorization: Bearer {token}
                      Content-type: application/octet-stream
                      If-Match: *

    Note this example for the If-Match key uses the * for its value. The * is a wildcard character telling Business Central to accept any etag value for the record. The etag node is returned in the json body of Post and Patch requests. It can be used to determine if a record has been updated by another user or application prior to your service making its update and error if the etag you are passing doesn’t match the etag in the system. The * overrides that etag validation check. You can use the actual value for the etag if you prefer.

    The json body will be the bytes for the file you are importing. For instance, a c# example would be:
                     byte[] bytes = File.ReadAllBytes(filePath), and you would pass the bytes
                     variable as the body to your httpclient or RestRequest object.

  3. Import your file: Post (Use post for this call, not Patch) to url: https://api.businesscentral.dynamics.com/v2.0/yourenvironmentname/api/microsoft/automation/v2.0/companies(companyId)/configurationPackages(yourconfigpackageid)/Microsoft.NAV.import
    The bound actions here are case sensitive, so use Microsoft.NAV.import (with the lower case i) and not Microsoft.NAV.Import (with a capital I).

    The header keys for this call should contain:
                     Authorization: Bearer {token}
    There is no json body for this call.

  4. Apply the file: Post (use post again, not Patch) to url: https://api.businesscentral.dynamics.com/v2.0/yourenvironmentname/api/microsoft/automation/v2.0/companies(companyId)/configurationPackages(configpackageid)/Microsoft.NAV.apply

    The header keys for this call should contain:
                   Authorization: Bearer {token}
    There is no json body for this call.

  5.  If you wanted to delete the Configuration Package record from Business Central after applying all the data. You can call the Delete method for the api.
    Delete using the url: https://api.businesscentral.dynamics.com/v2.0/yourenvironmentname/api/microsoft/automation/v2.0/companies(companyId)/configurationPackages(configpackageid)

    The header keys for this call should contain:
                   Authorization: Bearer {token}
    There is no json body for this call.

Try it with Postman!

You can use Postman to test these api calls after you get your App Registration setup in your Azure Active directly. Documentation on how to test the apis with postman can be found here under the Exploring the APIs with Postman and AAD authentication section.


After following the documentation at the link above, you should be able to authenticate. Note the redirect url below pictured below for the online version. This will need to be entered into your App Registration’s list of redirect urls. Also, pictured below is how I setup Postman for OAuth2.0 authentication. I will list the values for the variables after the pic.

Rapid-Start-automation-4

authUrl:
https://login.windows.net/yourtenantId/oauth2/authorize?resource=https://api.businesscentral.dynamics.com

your tenant id is the guid for the tenant you are connecting to.
accessTokenUrl:
https://login.windows.net/yourtenantId/oauth2/token?resource=https://api.businesscentral.dynamics.com

clientId: The Application (client) Id from your registered app’s Overview section in Azure Active Directory

secret: The secret you generated for your registered app and saved in a safe place.

I store all four variables above as global variables in Postman. Note, you can also use global variables in the urls above. For instance, yourtenantid can be another global variable that contains your tenant id.

What about coding in C# (or other languages)

Code Samples

In your app registration in Azure Active Directory, there is a Quickstart menu item that lets you choose from a number of different client types. I want to focus on a C# console app, so I’ll click on Daemon Application selection pictured below.

Rapid-Start-automation-5

Then I choose .NET Core Console in the menu that appears

Rapid-Start-automation-6

And I download the code sample from the page that displays.

If you need to change api permission for your app registration to be able to use the code sample, the download page will also give tell you want api permission you need to add (if any).

Rapid-Start-automation-7

After the download, I use the 1-Call-MSGraph console app to test my app registration. I also use that app a code sample for my own service to service app, connecting to Business Central. You can find that in the download at \active-directory-dotnetcore-daemon-v2-master\active-directory-dotnetcore-daemon-v2-master\1-Call-MSGraph.

Create a console app to connect to Business Central

The daemon-console.sln in the 1-Call-MSGraph folder of your download is a great starting point for learning how to use your app registration, but what if you wanted to use it to connect to Business Central?

Some authentication changes I made specifically to connect to Business Central are highlighted in the methods below. Two full c# files are listed at the end of this blog to give you more context and show you the libraries being used.

Note the scopes definition in the GetServiceToken method that I am using. You need to use this scope to connect to Business Central.

Also note that I am using the IConfidentialClientApplication interface’s ConfidentialClientApplicationBuilder.Create method in the SetConfidentialToketAsync method:

private static string GetServiceToken()
{
                 var scopes = new string[] { $"{Properties.Settings.Default.ApiBaseUrl}/.default" };
                 SetConfidentialTokenAsync(scopes).GetAwaiter().GetResult();
                 return m_ServiceToken;
}

private static async Task SetConfidentialTokenAsync(string[] scopes)
{
                 //AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

                 // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the                                                IConfidentialClientApplication

               // Even if this is a console application here, a daemon application is a confidential client application

                 m_ServiceToken = string.Empty;

                 IConfidentialClientApplication app;

                 app = ConfidentialClientApplicationBuilder.Create (Properties.Settings.Default.ClientId)
                                 .WithClientSecret(Properties.Settings.Default.ClientSecret)
                                 .WithAuthority(new Uri(String.Format("https://login.microsoftonline.com/{0}", Properties.Settings.Default.TenantId)))
                                 .WithRedirectUri(Properties.Settings.Default.RedirectUrl)
                                 .Build();

                 AuthenticationResult result = null;
                 try
                 {
                                 result = await app.AcquireTokenForClient(scopes)
                                                 .ExecuteAsync();
                                 Console.ForegroundColor = ConsoleColor.Green;
                                 Console.WriteLine("Token acquired");
                                 Console.ResetColor();
                 }
                 catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
                 {
                                 // Invalid scope. The scope has to be of the form "https://resourceurl/.default"
                                 // Mitigation: change the scope to be as expected
                                 Console.ForegroundColor = ConsoleColor.Red;
                                 Console.WriteLine("Scope provided is not supported");
                                 Console.ResetColor();
                 }

At the end of this blog are the two sample files I use in a demo app. The actual app is not available for download, as I’m just supplying you with ideas on how to create your own app.

You’ll notice I’m using properties to store my variables. Below are what those properties represent. You can still use an app.json file, etc., like they do in the daemon-console app to store the variables.

TenantId: Your Tenant ID

RedirectURL: http://localhost (this value needs to be in the list of Redirect Urls in your App Registration in Azure Active Directory).

ApiBaseUrl: https://api.businesscentral.dynamics.com

CompanyId: The company id of the Business Central company you are writing to. It’s found by calling the https://api.businesscentral.dynamics.com/v2.0/environmentname/api/ icrosoft/automation/v2.0/companies API

ClientId: The Application (client) Id from your app registration in Active Directory.

ClientSecret: The secret you created in your app registration

EnvironmentName: The name of the environment you are connecting to: Production, Sandbox, etc.

Try Standard APIs!

After you get your Authentication working and your console app writing to business central with the configurationPackages api, try authentication and writing with other apis.

Turns out you can now use the Oath2.0 authentication for service to service calls using standard apis as well. You’ll notice my Business Central code sample calls the Customer api using the same authentication method.

Click Here to download a PDF of the code.

If you have any additional questions please contact Innovia Consulting.

Click Here to View Ross's Webinar Using Automation APIs in Business Central – Deep Dive

Book Time with Your Customer Engagement Specialist

Ross Bottorf

Ross Bottorf

Ross Bottorf works as a Development Consultant at Innovia. Ross has over 10 years of experience as a Dynamics BC/NAV Developer. He graduated from Arizona State University and now resides in Tucson, Arizona, with his wife and son. Ross enjoys playing the guitar and loves music and living in the Southwest.

Related Posts