Azure API Management:为不同端点后端配置对应API密钥请求头
为Azure API不同后端添加对应API密钥的实现方案
核心思路
和你当前设置后端服务的逻辑一致,通过条件判断为不同路径的请求添加对应后端要求的API密钥请求头,同时建议将密钥存储在API管理的命名值中,避免硬编码泄露风险。
步骤1:存储API密钥到命名值
在Azure API管理的「命名值」面板中创建三个命名值,分别对应三个后端的密钥:
- 名称:
OfferBackendKey,值:填写offer后端的API密钥 - 名称:
ProductBackendKey,值:填写product后端的API密钥 - 名称:
CustomerBackendKey,值:填写customer后端的API密钥
步骤2:修改Inbound策略添加密钥头
在现有的set-backend-service逻辑后,为每个条件分支添加set-header策略,将对应密钥注入到请求头中(假设后端要求的密钥头名称为X-API-Key,如果后端要求不同,替换name属性即可):
<policies> <inbound> <base /> <!-- Start:Set Different backends and corresponding API keys --> <when condition="@(context.Request.Url.Path.StartsWith("/offer") || context.Request.Url.Path.StartsWith("/offer/"))"> <set-backend-service base-url="https://offerBackend" /> <set-header name="X-API-Key" exists-action="override"> <value>{{OfferBackendKey}}</value> </set-header> </when> <when condition="@(context.Request.Url.Path.StartsWith("/products"))"> <set-backend-service base-url="https://productBackend" /> <set-header name="X-API-Key" exists-action="override"> <value>{{ProductBackendKey}}</value> </set-header> </when> <when condition="@(context.Request.Url.Path.StartsWith("/customer"))"> <set-backend-service base-url="https://customerBackend" /> <set-header name="X-API-Key" exists-action="override"> <value>{{CustomerBackendKey}}</value> </set-header> </when> <!-- End:Set Different backends and corresponding API keys --> </inbound> </policies>
关键细节说明
- 条件判断优化:把原有的
Contains改为StartsWith,避免路径包含多个关键词时的误匹配(比如路径/offercustomer不会被错误识别为offer后端请求) - 密钥注入逻辑:
exists-action="override"表示如果请求中已有同名头,直接替换为后端要求的密钥,避免冲突 - 自定义密钥头:如果不同后端要求的密钥头名称不同(比如有的用
Authorization: Bearer {key}),可以单独调整每个分支的set-header配置,示例:<set-header name="Authorization" exists-action="override"> <value>Bearer {{CustomerBackendKey}}</value> </set-header>
内容的提问来源于stack exchange,提问作者Techie
相关产品推荐
相关产品推荐

