How to create Business Central Online Sandbox with API. AAD Authentication

Today is my 35 birthday! 

And it’s a nice tradition to give presents to the community on that day ūüôā So, i decided to share a knowledge about Business Central Admin and Automation APIs.

As this is quite a big topic, this will be a series, covers the next areas:

  • How to connect to Business Central Admin Center¬†(today)
  • How to remove Cloud Business Central Sandbox
  • How to create Cloud¬†Business Central¬†Sandbox
  • How to upload and install¬†extensions with additional exposed APIs to your¬†Cloud¬†Business Central¬†Sandbox
  • How to add licensed users from MS365¬†Admin Center to your¬†Cloud¬†Business Central¬†Sandbox
  • How to switch Cloud Business Central Sandbox UI To the Premium Mode
  • How to upload, Import and Apply Extended Configuration Pack
  • How to upload, Import and Apply¬†your custom configuration Pack
  • How to uninstall¬†extensions from your¬†Cloud Business Central Sandbox

I will try to post one blog per week, but let’s see. Life will adjust the schedule, approximately.¬†

Why do you need that?

Spinning up an online sandbox with the script could be useful in CI/CD process (if you don’t want to spin up Docker container) or if you have a solution with custom data, number of extensions and¬†would like to create a¬†custom branded sandbox for the potential customers, or any other cases.¬†

How to connect to Business Central Admin Center

In order to be able to create, manage, remove online Business Central Sandbox with API you need to be able to connect to the tenant.

Here is very nice description of the process https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api. But without real example following the scenario could be a challenge. 

Assume, you are a partner and you want to create a BC tenant for your new customer. 

Create new Azure account

In this step you will create new Azure account. If you already have Azure account just skip this step.

If you don’t have an Azure account yet, or you prefer to create a separate account for your demos, you can subscribe for it free of charge here: https://azure.microsoft.com/free/

Create new Azure Active Directory

In this step you will create new Azure Active Directory. As a result, you will get your own Azure domain name, something like mycompany.onmicrosoft.com

If you already have Azure Active Directory, that you want to use for Business Central, just skip this step.

  1. Log in to the Microsoft Azure portal (https://portal.azure.com/, and then select Create Resource.

image

  1. Choose Azure Active Directory, and then click Create.

image

  1. Provide a name for your organization, and the initial domain name (*.onmicrosoft.com), and then select the country for your Azure AD tenant. 

Note: Make sure you select a country that is supported by the Business Central service. For more information, see https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/compliance/apptest-countries-and-translations

image

  1. When the directory (Azure AD tenant) is created, you can proceed with adding users to it:

image

  1. Define the directory role for the users that you are creating:

image

6. Save password somewhere, you will need it to change later

  1. Click Create

Change password for your created user

Go to https://portal.office.com/account/ and Sign-In with the user, that you created on the previous step.

You will be prompted to change password.

Create Business Central tenant

In this step you will create new Business Central tenant for Azure Active directory, you created before. If you already have Business Central for that Azure Active directory just skip this step.

Once you have created a new Azure AD tenant in the country that you need, and added a user to that tenant, you can use that user account to sign up for a trial of Dynamics 365 Business Central from https://trials.dynamics.com/, and Microsoft will provision the localization that corresponds to the country you selected when you created the Azure AD tenant.

image

Click on Get Started and you will create Cloud Business Central tenant. 

Note: This will be your Production Business Central Tenant. For the current scenario we will use Sandbox tenant. 

image

Add more users to Business Central

In this step you will add more users to Business Central. If you don’t need that, and you are ok with only one user, just skip this step. 

  1. Go to https://admin.microsoft.com/Adminportal/
  2. Open Users -> Active Users  

image

3. Choose user and click Edit under Product Licensing section

4. Activate Dynamic 365 Business Central for IWs license

image

 5. Repeat for all users, that you want to have access to Business Central

Open Business Central Admin Center Portal

You will need Business Center Admin Portal, to quickly open Production or Sandbox Business Central tenants, to monitor status of Sandbox, and to get telemetry. This step is not mandatory, however it simplify switching between environments.

  1. Open https://home.dynamics.com and log-in using global admin user (you created before)
  2. Click on Synch Now you will have your Business Central Production tenant shortcut.

image

3. Right-click on Business Central shortcut and copy url

image

4. Paste that link to browser and add /admin in the end

image

5. You will see Business Central Admin Center

image

Configure Azure Active Directory (AAD) based authentication for Business Central API

In this step you will configure AAD based authentication for Business Central.

This step is mandatory. If you will not complete it – Business Central Admin and Automation APIs will not work.

  1. Sign in to the Azure portal.
  2. If your account gives you access to more than one, select your account in the top right corner, and set your portal session to the desired Azure AD tenant.
  3. In the left-hand navigation pane, select theAzure Active Directory 
  4. Select App registrations and then select New application registration.

image

5. When the¬†Create¬†page appears, enter your application’s registration information:¬†

  • Name:¬†Business Central Web Service Client
  • Application type:¬†Native
  • Redirect URI:¬†BusinessCentralWebServiceClient://auth
  • go to¬†Settings, and then under¬†API ACCESS, choose¬†Required permissions. Choose¬†Add, and then under¬†Add API Access, choose¬†Select an API¬†and search for the¬†Dynamics 365¬†¬†Choose¬†Dynamics 365, select¬†Delegated permissions, and then choose the¬†Done¬†button

image

6. Save Application Id

Create New-PremiumBCCloudSandBoxWithCustomData Power Shell Script

In order to run PS Script you need to create it. 

Open VSCode (or Power Shell IDE) and create new file New-PremiumBCCloudSandBoxWithCustomData.ps1

If you are new to Power Shell (like me a year ago ūüôā i definitely recommend you the latest blog from Freddy¬†https://freddysblog.com/2019/08/04/powershell-for-non-experts/¬†

image

This will be the main script file for the future blogs.

Initialize variables

To make things easier (for anyone, who will run this script) we will initialize variables outside of the functions

  • $url¬†=’https://api.businesscentral.dynamics.com’¬†– this is the main api url
  • $appId¬†‚Äď assign here Application Id from the previous step
  • $DAemail¬†‚Äď assign here user e-mail that you created before
  • $DApassword¬†‚Äď assign here password for that user (could be empty)
  • $tenantdomain¬†‚Äď assign here you active directory
  • $sandboxName¬†– assign here the name of your future sandbox (don’t start with digit)
  • $companyName¬†– assign here the new company name

image

Install Azure Modules

In order to be able to connect to Admin, Automation and Business Central APIs using AAD authentication you should install Azure Modules. 

Note! You should run it only once. Even if you will close script, Power Shell will save result of that.

Create Prerequisites section

image

Run (F8)

image

 

Create GetAuthHeader Function

With that function you will get a Bearer key in Base64 format, that you will pass later in every API call. 

image

 

				
					function GetAuthHeader
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
[string] $DAemail,
[string] $DApassword,
[Parameter(Mandatory=$true)]
[string] $tenantdomain,
[Parameter(Mandatory=$true)]
[string] $appId
)

Write-Host "Checking for AzureAD module..."
if (!$CredPrompt){$CredPrompt = 'Auto'}
$AadModule = Get-Module -Name "AzureAD" -ListAvailable
if ($AadModule -eq $null) {$AadModule = Get-Module -Name "AzureADPreview" -ListAvailable}
if ($AadModule -eq $null) {write-host "AzureAD Powershell module is not installed. The module can be installed by running 'Install-Module AzureAD' or 'Install-Module AzureADPreview' from an elevated PowerShell prompt. Stopping." -f Yellow;exit}
if ($AadModule.count -gt 1) {
$Latest_Version = ($AadModule | select version | Sort-Object)[-1]
$aadModule = $AadModule | ? { $_.version -eq $Latest_Version.version }
$adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
}
else {
$adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
}
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

if ($DApassword) {

$cred = [Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential]::new($DAemail, $DApassword)
$ctx = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new("https://login.windows.net/$tenantdomain")
$token = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($ctx, "https://api.businesscentral.dynamics.com", $appId, $cred).GetAwaiter().GetResult().AccessToken

if ($token) { Write-Host -ForegroundColor Green "Successfully connected to Cloud Business Central"}
if (!$token) { Write-Host -ForegroundColor Red "Connection to Cloud Business Central failed"}

return "Bearer $($token)"

}
else {

$authority = "https://login.windows.net"
$resource = "https://projectmadeira.com"
$clientRedirectUri = [uri]"BusinessCentralWebServiceClient://auth"

$authenticationContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext -ArgumentList "$authority/$tenantdomain"
$platformParameters = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters -ArgumentList ([Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Always)
$userIdentifier = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier -ArgumentList ($DAemail, [Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType]::RequiredDisplayableId)
$authenticationResult = $authenticationContext.AcquireTokenAsync($resource, $appId, $clientRedirectUri, $platformParameters, $userIdentifier).GetAwaiter().GetResult()

if ($authenticationResult.AccessToken) { Write-Host -ForegroundColor Green "Successfully connected to Cloud Business Central"}
if (!$authenticationResult.AccessToken) { Write-Host -ForegroundColor Red "Connection to Cloud Business Central failed"}

return "$($authenticationResult.AccessTokenType) $($authenticationResult.AccessToken)"
}
}
				
			

 

 

Create New-PremiumBCCloudSandBoxWithCustomData Function

This will be the main function, which will call other functions

image

				
					function New-PremiumBCCloudSandBoxWithCustomData {
param
(
[Parameter(Mandatory=$true)]
[string] $url,
[Parameter(Mandatory=$true)]
[string] $appId,
[Parameter(Mandatory=$true)]
[string] $DAemail,
[string] $DApassword,
[Parameter(Mandatory=$true)]
[string] $tenantdomain,
[Parameter(Mandatory=$true)]
[string] $sandboxName,
[Parameter(Mandatory=$true)]
[string] $companyName

)

$startTime=(Get-Date);
Clear-Host

# Connect to admin Center
$authHeaderDA = GetAuthHeader -DAemail $DAemail -DApassword $DApassword -tenantdomain $tenantdomain -appId $appId

Write-Host $authHeaderDA

$Elapsed = (Get-Date)-$startTime;

}
				
			

Run 

So, the script for now looks like that

image

Select variables and the main function, and press F8

You will see a Sign In page

image

Enter Password and click Sign In

Note! If you specified Password variable this page will not appear. 

As a result you will see a confirmation message together with Bearer Key

image

The script could be found here https://github.com/dkatson/BC-Scripts/blob/master/New-PremiumBCCloudSandBoxWithCustomData.ps1 

In the next blog

How to remove Online Business Central Sandbox with API

Enjoy!

Share Post:

Leave a Reply

About Me

DMITRY KATSON

A Microsoft MVP, Business Central architect and a project manager, blogger and a speaker, husband and a twice a father. With more than 15 years in business, I went from developer to company owner. Having a great team, still love to put my hands on code and create AI powered Business Central Apps that just works.

Follow Me

Recent Posts

Tags