Azure API管理:使用后端API的Oauth2

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

3
这是一个使其起作用的策略片段:

这里有一个使其运作的策略片段:

    <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团队的策略片段分支中 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

这些资源提供了有关如何将 Azure AD OAuth2 bearer token 添加到请求中以保护 API 的详细信息。

1
它现在实际上已经存在了: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 - Dibran
我在使用这个策略时一直收到内部服务器错误,"message": "表达式计算失败。", "expression": ""Bearer " + (String)((IResponse)context.Variables["bearerToken"]).Body.As<JObject>()["access_token"]", "details": "解析值时遇到意外字符: <。路径'',行0,请给予建议。 - Sai
1
这怎么能算是一个可接受的解决方案呢?每次请求都要额外调用一个API。然而,访问令牌的目的在于其具有过期时间,在令牌过期之前,不应该使用新的令牌。这对于生产负载设置来说是行不通的。需要对令牌进行缓存、验证令牌是否过期以及其他一些操作。Azure团队还没有找到一个合适的解决方案吗?抱歉,我对Azure感到沮丧,这真的很有帮助。 - Varesh
https://learn.microsoft.com/en-us/azure/api-management/authorizations-overview - undefined

0
你需要做的是在请求中添加一个头部 - 使用 set-header 策略将授权头设置为所需的值。如果您可以在策略中硬编码令牌,那么这将非常有效。
如果您不能这样做 - 那么您必须在策略内部组织 OAuth 流程,使用 send-request。简而言之,您要做的就是向 OAuth 终端发送您的应用程序 ID 和密钥,并解析其响应以获取令牌并将其附加到请求中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接