Azure APIM集成外部后端API OAuth2 Bearer令牌认证配置咨询
解决方案:使用APIM入站策略实现后端服务OAuth2客户端凭证自动授权
你之前尝试的APIM内置OAuth2.0服务配置,是用于验证调用APIM的前端请求身份的,并非用于APIM作为客户端向后端服务商发起认证的场景,和你的需求不匹配,直接用APIM自定义策略就能实现你要的效果,步骤如下:
步骤1:配置敏感参数为APIM命名值
为了避免硬编码敏感信息,先在APIM左侧菜单找到「命名值」,添加三个键值对:
- 第三方服务商Client ID,建议命名为
BackendOAuthClientId - 第三方服务商Client Secret,建议命名为
BackendOAuthClientSecret,类型选「密钥」加密存储 - 第三方Token端点地址,建议命名为
BackendOAuthTokenEndpoint
步骤2:配置入站自定义策略
找到你需要添加认证的API/操作,进入「策略」编辑界面,替换入站段为如下配置,可根据你Postman里的实际参数调整:
<policies> <inbound> <base /> <!-- 先从缓存查找已有的有效token --> <cache-lookup-value key="backend-oauth-token" variable-name="accessToken" /> <!-- 缓存无token时主动调用token接口获取 --> <choose> <when condition="@(!context.Variables.ContainsKey("accessToken"))"> <send-request mode="new" response-variable-name="tokenResponse" timeout="10" ignore-error="false"> <set-url>{{BackendOAuthTokenEndpoint}}</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=client_credentials&client_id={{"{{BackendOAuthClientId}}"}}&client_secret={{"{{BackendOAuthClientSecret}}"}}")</set-body> </send-request> <!-- 解析返回的token --> <set-variable name="accessToken" value="@(((IResponse)context.Variables["tokenResponse"]).Body.As<JObject>()["access_token"].ToString())" /> <!-- 存入缓存,缓存时间设置比token实际过期时间短1-2分钟,避免使用过期token --> <cache-store-value key="backend-oauth-token" value="@((string)context.Variables["accessToken"])" duration="3540" /> </when> </choose> <!-- 给后端请求添加Authorization头 --> <set-header name="Authorization" exists-action="override"> <value>@($"Bearer {((string)context.Variables["accessToken"])}")</value> </set-header> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error> </policies>
注意事项
- 如果你Postman里的token请求还需要传scope等额外参数,直接在set-body的表单里添加对应参数即可
- 如果你的APIM是消费层、开发者层等不支持内置缓存的层级,可去掉缓存相关配置,每次请求都获取token,或者改用外部缓存
- 若服务商的token返回格式和标准OAuth2不同,自行调整解析access_token的逻辑即可
内容的提问来源于stack exchange,提问作者Steven
相关产品推荐
相关产品推荐

