经验教训 - 多注意 chatgpt 输出的内容!
主要问题是 C# 代码块的语法。这是工作方针:
<policies>
<inbound>
<base />
<choose>
<when condition="@(!context.Variables.ContainsKey("cachedAccessToken") || DateTime.UtcNow >= (DateTime)context.Variables["tokenExpiry"])">
<set-backend-service id="apim-generated-policy" backend-id="func-amx-api-dev-001" />
<send-request mode="new" response-variable-name="tokenResponse" timeout="20" ignore-error="false">
<set-url>{{baseurl}}.azurewebsites.net/token</set-url>
<set-method>POST</set-method>
<set-header name="Content-Type" exists-action="override">
<value>application/x-www-form-urlencoded</value>
</set-header>
<set-body>@("grant_type=password&username={{user}}&password={{AmxPassword}}")</set-body>
</send-request>
<set-variable name="cachedAccessToken" value="@((String)((IResponse)context.Variables["jwt"]).Body.As<JObject>()["access_token"])" />
<set-variable name="tokenExpiry" value="@((String)((IResponse)context.Variables["jwt"]).Body.As<JObject>()["expires_in"])" />
<cache-store-value key="cachedAccessToken" value="@((String)context.Variables["cachedAccessToken"])" duration="3600" caching-type="internal" />
<cache-store-value key="tokenExpiry" value="@((String)context.Variables["tokenExpiry"])" duration="3600" caching-type="internal" />
</when>
<otherwise>
<cache-lookup-value key="cachedAccessToken" variable-name="cachedAccessToken" />
<cache-lookup-value key="tokenExpiry" variable-name="tokenExpiry" />
</otherwise>
</choose>
<set-header name="Authorization" exists-action="override">
<value>@{
return $"Bearer {(String)context.Variables["cachedAccessToken"]}";
}</value>
</set-header>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
我还将策略移动到一个单独的文件,并使用以下二头肌在 apim 操作级别部署:
resource apiPolicy 'Microsoft.ApiManagement/service/apis/operations/policies@2022-09-01-preview' = {
name: '${apimName}/amxapi_v1_0_0/entity/policy'
properties: {
value: loadTextContent('./createEntityPolicy.xml')
}
}