You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell导入Swagger至Azure APIM遇AAD认证及本地文件读取问题

问题:导入AAD保护的Swagger到Azure APIM失败及本地文件导入方法

问题场景

使用PowerShell命令导入公网无认证的Swagger(如https://petstore3.swagger.io/api/v3/openapi.json)到Azure APIM可正常完成,但导入受AAD保护的Swagger时持续报错。

执行的PowerShell命令:

$context = New-AzApiManagementContext -ResourceGroupName $resourceGroupName -ServiceName $apimServiceName
$Commonapi = Import-AzApiManagementApi -Context $context -SpecificationUrl $globalCatalog -SpecificationFormat OpenApi -Path $apiPath

报错信息:

Error Code: ValidationError Error Message: One or more fields contain incorrect values: Request Id: 78ee1174-074c-4b84-87ba-95f93313b055 Error Details:  [Code= ValidationError, Message= Parsing     
     | error(s): Failed to import from specified resource https:fqdn/apipath/Swagger/v1/swagger.json: The remote name could not be resolved:
     | 'aud-globalcatalog-kcwg11.dev.kpmg.com'., Target= representation]

解决方案1:处理AAD保护的Swagger导入

Import-AzApiManagementApi直接通过SpecificationUrl访问受AAD保护的地址时,不会自动携带认证信息,导致访问失败。需先获取AAD令牌并下载Swagger内容,再导入:

  1. 获取目标Swagger对应的AAD访问令牌
  2. 携带令牌下载Swagger内容
  3. 通过Specification参数传入内容完成导入

示例代码:

# 替换为你的Swagger服务对应的AAD资源ID/受众URL
$aadResource = "https://aud-globalcatalog-kcwg11.dev.kpmg.com"
$token = (Get-AzAccessToken -ResourceUrl $aadResource).Token

# 下载受保护的Swagger内容
$swaggerContent = Invoke-RestMethod -Uri $globalCatalog -Headers @{ Authorization = "Bearer $token" }

# 导入到Azure APIM
$context = New-AzApiManagementContext -ResourceGroupName $resourceGroupName -ServiceName $apimServiceName
$Commonapi = Import-AzApiManagementApi -Context $context -Specification $swaggerContent -SpecificationFormat OpenApi -Path $apiPath

注意:执行命令的账号需同时拥有访问该Swagger地址的AAD权限,以及Azure APIM的管理权限。


解决方案2:导入本地swagger.json文件

直接读取本地文件内容,通过Specification参数传入即可,无需依赖远程地址:

示例代码:

$context = New-AzApiManagementContext -ResourceGroupName $resourceGroupName -ServiceName $apimServiceName
# 替换为本地swagger.json的实际路径
$localSwaggerPath = "C:\your-local-path\swagger.json"
$swaggerContent = Get-Content $localSwaggerPath -Raw

$Commonapi = Import-AzApiManagementApi -Context $context -Specification $swaggerContent -SpecificationFormat OpenApi -Path $apiPath

内容的提问来源于stack exchange,提问作者Aji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 12:40:30