我有一个 Azure Function App,最近使用“az apim api import”cli 命令导入到 Azure APIM 中。这将是发布管道的一部分。到目前为止,导入的 API 在我的测试中可以正常工作。在测试期间,我需要手动将 x-functions-key 包含在我的标头中才能工作。为了避免这样做,我:
当我测试它时(来自 APIM 测试门户)。我收到“401”。查看跟踪日志,标头中不包含 x-functions-key 键。我错过了什么?
顺便说一句。对使用 CLI 导入函数应用程序与通过门户导入函数应用程序进行了比较,我注意到以下差异:
-- VIA CLI - 后端目标正在使用 HTTP(s) 端点。
-- VIA PORTAL - 后端目标屏幕现在看起来有所不同。例子。它有 Azure 资源作为选项。该值指向指定的值。
更新:能够通过使用 API 策略解决问题。将 SetHTTPheader 添加到后端基本策略。可以在这里找到说明:
在寻求通过 CI/CD 解决这个问题的过程中,我一直在寻找这篇文章——以防其他人遇到同样的问题——这就是我如何解决它的,尽管是以一种 HACK 的方式。
重新总结一下问题 - 每当我直接通过 Azure 门户添加功能时,我都可以使用
Ocp-Apim-Subscription-Key
标头直接通过 APIM 网关访问它们。但是,当我在使用 OpenApi 规范的管道运行期间导入它们时,APIM 会创建与功能键对应的命名值,但它不会自动将 x-functions-key
标头/code
参数添加到入站请求中。这意味着导入的函数需要 Ocp-Apim-Subscription-Key
标头以及 x-functions-key
标头或 code
参数。
首先 - 我正在使用 Azure CLI 和 OpenApi 规范来发布部署后的函数。
az apim api import `
--path 'my-function' `
-g 'rg-someresourcegroup' `
--api-id 'MyFunction' `
--description 'This is my function' `
--service-name 'apim-instance' `
--specification-format 'OpenApi' `
--specification-url 'https://func-myfunction.azurewebsites.net/api/openapi/v3.json' `
--display-name 'MyFunction' `
--api-version 'v1' `
--api-version-set-id 'MyFunction-v1' `
--subscription-key-header-name "Ocp-Apim-Subscription-Key" `
--subscription-key-query-param-name "subscription-key" `
--protocols "https"
以这种方式在 APIM 中创建的命名值使用 Azure 函数资源名称 +
key
- 在上面的示例中为 func-myfunctionkey
。我使用参数 $WebAppName
将此值传递到我的 CI/CD 任务和 Powershell 脚本中。
这是我用来将
x-functions-key
自动添加到函数中的策略片段(如果需要,您也可以修改它以使用 ?code=
参数)。
<policies>
<inbound>
<base />
<set-header name="x-functions-key" exists-action="override">
<value>@@function-key@@</value>
</set-header>
<!-- Other policy stuff here -->
</inbound>
<!-- Other policy stuff here -->
</policies>
然后在我的管道中 - 我正在使用 powershell 执行“替换令牌”式任务并将此策略文档上传到 APIM 端点。
Write-Host `n"Creating default inbound policy for Api: $ApiName"
$apimContext = New-AzApiManagementContext -ResourceGroupName $ResourceGroupName -ServiceName $ServiceName
$path = './apim-default-api-policy.xml'
## Replace the @@function-key@@ with the correct value.
$xml = (Get-Content -Raw $path) -Replace "@@function-key@@", "{{$WebAppName-key}}"
Set-AzApiManagementPolicy -Context $apimContext `
-Format 'application/vnd.ms-azure-apim.policy.raw+xml' `
-ApiId $ApiName `
-Policy $xml
Write-Host `n"Set policy for $ApiName"
请注意,我正在使用
az
CLI 进行导入,并使用 Azure Powershell 进行策略更新 - 在撰写本文时 (05/2023) - az
CLI 似乎不支持这样的策略操作 - 希望如此,此功能已添加。
编辑 - 我最初纯粹使用
az
CLI 来解决这个问题 - 我后来发现应该可以使用 Azure Powershell 和 set-backend APIM 策略来完成此操作。