【问题标题】:Azure API Management: Oauth2 with backend APIAzure API 管理:带有后端 API 的 Oauth2
【发布时间】:2018-11-23 15:53:13
【问题描述】:

我有一个后端 API,我想使用 Azure API 管理进行代理。 此后端 API 要求我提供 Bearer Oauth2 令牌。 我想使用 Azure APIM 为我处理 Oauth2 流,并且我想公开一个非常简单的 API,供客户端应用程序使用。我想避免我的客户端应用程序使用 Oauth2。 如何使用 APIM 处理它?我发现很多示例演示了如何使用 Oauth2 保护后端 API,但这不是我想要实现的用例。 谢谢。

【问题讨论】:

    标签: api azure oauth azure-api-management


    【解决方案1】:

    这是一个使这项工作发挥作用的策略 sn-p:

        <send-request ignore-error="true" timeout="20" response-variable-name="bearerToken" mode="new">
            <set-url>{{authorizationServer}}</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>   
                @{
                    return "client_id={{clientId}}&resource={{scope}}&client_secret={{clientSecret}}&grant_type=client_credentials";
                }
            </set-body>
        </send-request>
    
        <set-header name="Authorization" exists-action="override">
            <value>
                @("Bearer " + (String)((IResponse)context.Variables["bearerToken"]).Body.As<JObject>()["access_token"])
            </value>
        </set-header>
    
        <!--  We do not want to expose our APIM subscription key to the backend API  -->
            <set-header exists-action="delete" name="Ocp-Apim-Subscription-Key"/>
    

    发件人:https://github.com/orangetoken/api-management-policy-snippets/blob/master/Snippets/Add%20Azure%20AD%20OAuth2%20bearer%20token%20to%20request%20to%20AD%20protected%20API.xml

    以及 APIM 团队的 APIM 政策 sn-ps 分支 https://github.com/Azure/api-management-policy-snippets/blob/master/examples/Get%20OAuth2%20access%20token%20from%20AAD%20and%20forward%20it%20to%20the%20backend.policy.xml

    【讨论】:

    • 使用此策略时,我不断收到内部服务器错误,“消息”:“表达式评估失败。”,“表达式”:“\”Bearer \" + (String)((IResponse)context.Variables [\"bearerToken\"]).Body.As()[\"access_token\"]", "details": "解析值时遇到意外字符:<.path line>
    【解决方案2】:

    您需要做的是向请求添加一个标头 - 使用 set-header 策略将 Authorization 标头设置为所需的值。如果您可以在策略中对令牌进行硬编码,那将很有效。

    如果您不能 - 您必须使用发送请求在策略内组织 OAuth 流程。简而言之,您要做的就是将应用程序 ID 和密钥发送到 OAuth 端点,并解析其响应以获取令牌并将其附加到请求中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多