azure-api-management - 支持关闭时 Azure Api 管理返回详细错误,包括 oath 令牌
问题描述
我正在研究 API 管理,后端使用 oauth 客户端凭据进行验证。如果后端关闭,我会收到 200 的响应和如下详细错误。
{
"error": {
"name": "StatusCodeError",
"statusCode": 404,
"message": "HTTP Error 404. The requested resource is not found.",
"options": {
"url": "https://...net.au/api/case/mycases/",
"method": "GET",
"headers": {
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhb....."
},
"simple": true,
"resolveWithFullResponse": false,
"transform2xxOnly": false
},
"response": {
"statusCode": 404,
"body": "HTTP Error 404. The requested resource is not found.",
"headers": {
"content-length": "315",
"content-type": "text/html; charset=us-ascii",
"server": "Microsoft-HTTPAPI/2.0 Microsoft-HTTPAPI/2.0",
"date": "Fri, 14 Jun 2019 02:12:36 GMT",
"connection": "close"
},
"request": {
"uri": {
"protocol": "https:",
"slashes": true,
"auth": null,
"host": ".....",
"port": 443,
"hostname": "....net.au",
"hash": null,
"search": null,
"query": null,
"pathname": "/api/case/mycases/",
"path": "/api/case/mycases/",
"href": "https://...."
},
"method": "GET",
"headers": {
"Authorization": "Bearer eyJ0eXAiO....."
}
}
}
},
"status": 501
}
我只想在调用 api 时返回这样的响应。并隐藏所有额外的细节,包括访问令牌。
{
"error": {
"name": "StatusCodeError",
"statusCode": 404,
"message": "HTTP Error 404. The requested resource is not found.",
}
}
根据下面的答案,我已经更新了我的政策,当后端离线时我得到了想要的响应,但是当后端在线时我得到了空响应。
<choose>
<when condition="@{
var token = context.Response.Body.As<JToken>();
if (token is JObject){
return true;
}
return false;
}">
<return-response>
<set-status code="404" reason="NotFound" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>{
"error": {
"name": "StatusCodeError",
"statusCode": 404,
"message": "HTTP Error 404. The requested resource is not found.",
}
}</set-body>
</return-response>
</when>
</choose>
解决方案
有两种情况可以从 APIM 获得 404 响应。一种是当您尝试调用 APIM 不知道的 API/操作时,在这种情况下 APIM 将生成 404 响应并且它会非常短,就像您的第二个响应一样。
另一种情况是 APIM 识别 API/操作,调用后端,后端响应 404。在这种情况下,APIM 不会将此视为问题,而只是将后端响应中继给客户端。您在第一个示例中的内容看起来像是后端会回复的内容。您可以通过从 Azure 门户中的测试控制台进行调用并检查提供的跟踪来确认这一点。
因此,您要做的是用您选择的一种替换 404 响应的正文,这可以通过策略轻松完成。在任何范围内,都按照以下思路放置一些东西:
<outbound>
<base/>
<choose>
<when condition="@(context.Response.StatusCode == 404)">
<return-response>
<set-status code="404" reason="NotFound">
<set-header name="Content-Type">
<value>application/json</value>
</set-header>
<set-body>{
"error": {
"name": "StatusCodeError",
"statusCode": 404,
"message": "HTTP Error 404. The requested resource is not found.",
}
}</set-body>
</return-response>
</when>
</choose>
</outbound>
推荐阅读
- c# - 如何使用c#执行vsjitdebugger.exe
- flexbox - bootstrap 的 flex-column 填充全宽,如何不拉伸到全宽?
- javascript - 数组帮助 | JS
- solr - 在 Solr 7.x 中,如何仅对逗号而不是空格或其他特殊字符进行标记?
- javascript - Javascript绑定函数未按预期传递参数
- c# - c# mvc中文本框中的意义值是字符串还是数字
- reactjs - React Native SectionList 替换数据键
- javascript - 在javascript中使用文件列表进行多次拖放
- powershell - Get-PartitionSupportedSize 失败并出现错误
- java - 在 Spring Data 中分离实体