Azure API Management授权后无法获取后端服务JSON响应
问题解决:Azure API Management验证Bearer令牌后无法获取后端Flask服务的JSON响应
问题原因
你的入站策略中,当Bearer令牌验证通过时,使用了<return-response>节点直接返回提示文本,这个操作会终止整个请求流程,不会将请求转发到后端的Flask服务,因此无法获取到后端返回的JSON数据。
修改后的策略代码
将验证成功分支里的<return-response>块移除,保留验证失败的拦截逻辑即可:
<policies> <inbound> <base /> <!-- 从Authorization头中提取Bearer令牌 --> <set-variable name="Bearer Token" value="@(context.Request.Headers.GetValueOrDefault("Authorization", "").Substring(7))" /> <!-- 从Key Vault中获取密钥 --> <set-variable name="KeyVaultSecret" value="{{secret}}" /> <!-- 检查Bearer令牌和Key Vault密钥是否为字符串且长度一致 --> <choose> <when condition="@(context.Variables["Bearer Token"] is string && context.Variables["KeyVaultSecret"] is string && ((string)context.Variables["Bearer Token"]).Length == ((string)context.Variables["KeyVaultSecret"]).Length)"> <!-- 对比Bearer令牌和Key Vault密钥 --> <choose> <when condition="@($"{context.Variables["Bearer Token"]}" == $"{context.Variables["KeyVaultSecret"]}")"> <!-- 移除return-response,让请求继续转发到后端 --> </when> <otherwise> <return-response> <set-status code="401" reason="Unauthorized" /> <set-body>@($"Bearer令牌与密钥不匹配。Bearer令牌: {context.Variables["Bearer Token"]}, Key Vault密钥: {context.Variables["KeyVaultSecret"]}")</set-body> </return-response> </otherwise> </choose> </when> <otherwise> <return-response> <set-status code="400" reason="Bad Request" /> <set-body>@($"Bearer令牌与密钥不匹配。Bearer令牌: {context.Variables["Bearer Token"]}, Key Vault密钥: {context.Variables["KeyVaultSecret"]}")</set-body> </return-response> </otherwise> </choose> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error> </policies>
关键修改说明
- 移除验证成功分支中的
<return-response>节点,APIM会自动进入<backend>阶段,将请求转发到你的Flask服务,获取后端返回的JSON响应后再返回给客户端 - 保留所有验证失败场景的
<return-response>,确保未授权或格式错误的请求被及时拦截,不会到达后端服务
内容的提问来源于stack exchange,提问作者Ashu
相关产品推荐
相关产品推荐

