关于如何通过Admin Center API来管理BC SaaS的环境

中国語

各位读者好。
在几个月前,我们曾经讨论过如何通过Admin Center API来安装AppSource的扩展 how to install AppSource Apps via Admin Center API. 最近我看到一个有趣的问题,能否通过Admin Center API来管理SaaS的环境呢?

当然,这是可能的,在这篇博客中,让我们一起来尝试一下。(认证部分的内容和 how to install AppSource Apps via Admin Center API 中一样)

本次测试需要的工具:

Authenticate.ps1: 此示例向 Azure Active Directory (AAD) 进行身份验证并获取访问令牌。

Environments.ps1: 此文件包含可用于管理客户环境的 API 调用示例。

简单来说,我们只需两个步骤即可完成此操作。 第一个是身份验证Authentication,第二个是管理环境Managing Environment

身份验证 Authentication

前提条件:
・Microsoft Azure App Registrations (如果您还没有,请先订阅 Microsoft Azure)

1. 登录到Azure Portal.

2. 在查询中输入App registrations,然后点击链接.

3. 选择New registration.

4. 输入 Name 并选择 who can use this application or access this API, 然后点击 Register.
例如:
Name: Business Central App Install API
Who can use this application or access this API: Accounts in this organizational directory only.

5. 点击Overview页面上的Add a Redirect URI.

6. 点击Add a platform.

7. 选择Mobile and desktop applications.

8. 添加 http://localhost 到Custom redirect URIs中, 然后点击Configure.

更新成功。

9. 选择API permissions, 然后点击 Add a permission.

10. 选择 Dynamics 365 Business Central.

11. 再选择Delegated permissions.

12. 选择所有的权限, 然后点击 Add permissions. (这里你可以选择最小的权限)

13. 选择Manifest, 找到”allowPublicClient”并把它的值修改为true, 然后点击Save.

14. 退回到overview页面

现在你可以更新Authenticate.ps1中的Parameters参数.

例:

15. 用管理员打开 Windows PowerShell ISE, 然后允许 Install-Module AzureAD命令.

Add-Type -Path “C:\Program Files\WindowsPowerShell\Modules\AzureAD\2.0.2.130\Microsoft.IdentityModel.Clients.ActiveDirectory.dll” # Install-Module AzureAD to get this

选择是Yes.

安装完成.

Note: 下载完成后,需要更新文件夹的路径。 否则会报错。

最新版本是2.0.2.130。(2021/04/16)

到这里需要的设置就全部完成了.
例:

# This sample authenticates to Azure Active Directory (AAD) an obtains an access token.
# The access token can be used for authenticating to Business Central APIs.


# Parameters
$aadAppId = "3263173a-0507-4ef5-9f25-ca4a5c47ebec"        # partner's AAD app id
$aadAppRedirectUri = "http://localhost"                   # partner's AAD app redirect URI
$aadTenantId = "d8f36038-1f93-4543-affc-5dc92b6ee871"    # customer's tenant id


# Load Microsoft.IdentityModel.Clients.ActiveDirectory.dll
Add-Type -Path "C:\Program Files\WindowsPowerShell\Modules\AzureAD\2.0.2.130\Microsoft.IdentityModel.Clients.ActiveDirectory.dll" # Install-Module AzureAD to get this


# Get access token
$ctx = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new("https://login.microsoftonline.com/$aadTenantId")
$redirectUri = New-Object -TypeName System.Uri -ArgumentList $aadAppRedirectUri
$platformParameters = New-Object -TypeName Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters -ArgumentList ([Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Always)
$accessToken = $ctx.AcquireTokenAsync("https://api.businesscentral.dynamics.com", $aadAppId, $redirectUri, $platformParameters).GetAwaiter().GetResult().AccessToken
Write-Host -ForegroundColor Cyan 'Authentication complete - we have an access token for Business Central, and it is stored in the $accessToken variable.'

# Peek inside the access token (this is just for education purposes; in actual API calls we'll just pass it as one long string)
$middlePart = $accessToken.Split('.')[1]
$middlePartPadded = "$middlePart$(''.PadLeft((4-$middlePart.Length%4)%4,'='))"
$middlePartDecoded = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($middlePartPadded))
$middlePartDecodedPretty = (ConvertTo-Json (ConvertFrom-Json $middlePartDecoded))
Write-Host "Contents of the access token:"
Write-Host $middlePartDecodedPretty

16. 点击Windows PowerShell ISE中的Run all commands.

输入登录信息.

选择Accept (承諾).

如果你看到下面的命令 “Authentication complete – we have an access token for Business Central, and it is stored in the $accessToken variable.“,并且没有任何错误信息,这表示认证Authentication成功了。

Note: 如果App registrations设置不完全的话,可能会出现以下权限错误。

“0” 個の引数を指定して “GetResult” を呼び出し中に例外が発生しました: “AADSTS650057: Invalid resource. The client has requested access to a resource which is not listed in the requested permissions in the client’s application registration. Client app ID: 3263173a-0507-4ef5-9f25-ca4a5c47ebec(Business Central App Install API). Resource value from request https://api.businesscentral.dynamics.com. Resource app ID: 996def3d-b36c-4153-8607-a6fd3c01b89f. List of valid resources from app registration: 00000003-0000-0000-c000-000000000000.

测试视频:

管理环境 Managing Environments

一旦认证Authentication完成, 剩下的就非常简单了。你可以参考 Environments.ps1 中如何去管理环境。

例如: Get, Create, Copy 和 Delete.
获取当前所有环境的一览表:

# Get list of environments
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

获取一个环境的信息:

# Get list of environments
$newEnvironmentName = "SandboxUS"
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$newEnvironmentName" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

创建一个新的环境:

# Create new environment
$newEnvironmentName = "MyNewSandboxViaAPI"
$response = Invoke-WebRequest `
    -Method Put `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$newEnvironmentName" `
    -Body   (@{
                 EnvironmentType = "Sandbox"
                 CountryCode     = "JP"
              } | ConvertTo-Json) `
    -Headers @{Authorization=("Bearer $accessToken")} `
    -ContentType "application/json"

复制一个生产环境到沙盒环境:

# Copy production environment to a sandbox environment
$environmentName = "Production"
$newEnvironmentName = "MyNewSandboxAsACopy"
$response = Invoke-WebRequest `
    -Method Post `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$environmentName" `
    -Body   (@{
                 EnvironmentName = $newEnvironmentName
                 Type            = "Sandbox"
              } | ConvertTo-Json) `
    -Headers @{Authorization=("Bearer $accessToken")} `
    -ContentType "application/json"

删除环境:

# Delete an environments
$newEnvironmentName = "TestSandbox"
$response = Invoke-WebRequest `
    -Method Delete `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$newEnvironmentName" `
    -Headers @{Authorization=("Bearer $accessToken")}

The Create, Copy, and Delete operations are asynchronous. The response objects are returned before the underlying operation has completed. The final results of the operation are reflected in the ‘status’ field of the environment that the operations affect. In practice this means that polling of the ‘Get Environments’ endpoints must be done to determine if the given operation was successful.

其他:
获取支持设置:

# Get support settings
$environmentName = "MyNewSandboxAsACopy"
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/support/applications/businesscentral/environments/$environmentName/supportcontact" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

获取特定环境使用的存储(数据库和文件)(以 KB 为单位):

# Get storage (database and file) used by an environment in KB
$environmentName = "Production"
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$environmentName/usedstorage" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

获取所有环境使用的存储(数据库和文件):

# Get storage (database and file) across all environments
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/environments/usedstorage" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

获取所有租户配额:

# Get all tenant quotas
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/environments/quotas" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

你可以在微软文档 Business Central Administration Center API 中找到更多。

以上

ZHU

コメント

Copied title and URL