Azure API Management: Oauth2 with backend API



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

下面是实现此目的的策略片段:

    <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 策略片段分支上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

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

如果不能 - 则必须使用 send-request 在策略内组织 OAuth 流。简而言之,你要做的是将应用 ID 和机密发送到 OAuth 终结点,并解析其响应以获取令牌并将其附加到请求。

最新更新