如何通过PowerShell或Azure CLI为Azure API Management授权提供商添加连接
可以通过PowerShell或Azure CLI为Azure API Management授权提供商添加连接
目前Azure API Management暂无专门的PowerShell Cmdlet或Azure CLI命令直接创建授权连接,但可通过调用Azure管理REST API的Authorization - Create Or Update接口实现,以下是具体操作方案:
一、PowerShell 实现(使用Invoke-AzRestMethod)
基于已创建的授权提供商,构造连接创建请求即可,示例代码如下:
function Add-AuthorizationConnection { [CmdletBinding()] param ( [string]$subscriptionId, [string]$environment, [string]$tenantName, [string]$connectionName, # 自定义连接名称 [string]$clientId, # AAD应用客户端ID [string]$clientSecret # AAD应用客户端密钥 ) # 构造API请求URL $apiUrl = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/test-rg-$environment/providers/Microsoft.ApiManagement/service/apim-test-$environment-xyz/authorizationProviders/testdevhealthcarewsxyz-$tenantName/authorizations/$connectionName?api-version=2022-08-01" # 构造请求体(客户端凭证模式) $body = @" { "properties": { "displayName": "$connectionName", "identityProvider": "aad", "oauth2": { "grantTypes": { "clientCredentials": { "clientId": "$clientId", "clientSecret": "$clientSecret" } } } } } "@ # 发送请求(需先通过Connect-AzAccount登录Azure) $response = Invoke-AzRestMethod -Path $apiUrl -Method PUT -Payload $body return $response }
说明:
- 调用前需执行
Connect-AzAccount完成Azure登录,无需手动传入accessToken,Invoke-AzRestMethod会自动获取上下文凭证connectionName需保证在对应授权提供商下唯一clientId和clientSecret需为拥有目标资源(示例中为https://dicom.healthcareapis.azure.com)访问权限的AAD应用凭证
二、Azure CLI 实现(使用az rest)
通过az rest命令直接调用REST API创建连接,示例命令如下:
az rest \ --method PUT \ --uri "/subscriptions/{subscriptionId}/resourceGroups/test-rg-{environment}/providers/Microsoft.ApiManagement/service/apim-test-{environment}-xyz/authorizationProviders/testdevhealthcarewsxyz-{tenantName}/authorizations/{connectionName}?api-version=2022-08-01" \ --body '{ "properties": { "displayName": "{connectionName}", "identityProvider": "aad", "oauth2": { "grantTypes": { "clientCredentials": { "clientId": "{clientId}", "clientSecret": "{clientSecret}" } } } } }'
说明:
- 将命令中所有
{xxx}占位符替换为实际值- 调用前需执行
az login完成Azure登录
注意事项
- 需使用与授权提供商创建时一致的API版本(示例为2022-08-01)
- 确保AAD应用凭证拥有目标资源的访问权限
- 连接名称在同一授权提供商范围内需唯一
内容的提问来源于stack exchange,提问作者One Developer
相关产品推荐
相关产品推荐

