Azure API 管理 : Using OAuth to secure a connection between the gateway and a backend?

标签 azure oauth azure-api-management

我们有一个受标准 OAuth 凭据流保护的现有后端。我们正在将所有流量转移到通过 Azure API 网关,并发现以下使用 OAuth 的策略(来源:Use OAuth2 for authorization between the gateway and a backend)。

<!-- The policy defined in this file provides an example of using OAuth2 for authorization between the gateway and a backend. -->
<!-- It shows how to obtain an access token from AAD and forward it to the backend. -->

<!-- Send request to AAD to obtain a bearer token -->
<!-- Parameters: authorizationServer - format https://login.windows.net/TENANT-GUID/oauth2/token -->
<!-- Parameters: scope - a URI encoded scope value -->
<!-- Parameters: clientId - an id obtained during app registration -->
<!-- Parameters: clientSecret - a URL encoded secret, obtained during app registration -->

<!-- Copy the following snippet into the inbound section. -->

<policies>
  <inbound>
    <base />
      <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>

      <!--  Don't expose APIM subscription key to the backend. -->
      <set-header exists-action="delete" name="Ocp-Apim-Subscription-Key"/>
  </inbound>
  <backend>
    <base />
  </backend>
  <outbound>
    <base />
  </outbound>
  <on-error>
    <base />
  </on-error>
</policies>

但是,该策略似乎没有重用 token ,因此每次调用都会获取一个新 token 。这不是最佳的,主要是因为性能,但也因为我们与 Auth0 的协议(protocol)对这些调用的数量有限制。

在网关和后端之间进行调用时,有没有办法重用 token (如果它仍然有效)?

最佳答案

尝试使用cache-store-value和cache-get-value将 token 存储在缓存中。如果您事先检查 token ,则可以将 int 放入缓存中,并将其过期时间设置为 ttl。只要确保有一个后备逻辑,以防缓存的 token 不起作用。

没有简单的方法来重用策略,因此重试部分可能看起来很麻烦。但仅当您想重试调用对缓存 token 的 401 响应时才需要这样做。

<policies>
    <inbound>
        <base />
        <cache-lookup-value key="bearerToken" variable-name="bearerToken" />
        <choose>
            <when condition="@(!context.Variables.ContainsKey("bearerToken"))">
                <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>@("client_id={{clientId}}&resource={{scope}}&client_secret={{clientSecret}}&grant_type=client_credentials")</set-body>
                </send-request>
                <set-variable name="bearerToken" value="@((string)((IResponse)context.Variables["bearerToken"]).Body.As<JObject>()["access_token"])" />
                <cache-store-value key="bearerToken" value="@((string)context.Variables["bearerToken"])" duration="60" />
                <set-variable name="cachedToken" value="@(false)" />
            </when>
            <otherwise>
                <set-variable name="cachedToken" value="@(true)" />
            </otherwise>
        </choose>

        <!--  Don't expose APIM subscription key to the backend. -->
        <set-header exists-action="delete" name="Ocp-Apim-Subscription-Key"/>
    </inbound>
    <backend>
        <retry condition="@((bool)context.Variables["cachedToken"] && context.Response.StatusCode == 401)" count="1" interval="0" first-fast-retry="true">
            <choose>
                <when condition="@(context.Response.StatusCode == 401)">
                    <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>@("client_id={{clientId}}&resource={{scope}}&client_secret={{clientSecret}}&grant_type=client_credentials")</set-body>
                    </send-request>
                    <set-variable name="bearerToken" value="@((string)((IResponse)context.Variables["bearerToken"]).Body.As<JObject>()["access_token"])" />
                    <cache-store-value key="bearerToken" value="@((string)context.Variables["bearerToken"])" duration="60" />
                    <set-variable name="cachedToken" value="@(false)" />
                </when>
            </choose>

            <set-header name="Authorization" exists-action="override">
                <value>@("Bearer " + (string)context.Variables["bearerToken"])</value>
            </set-header>

            <forward-request />
        </retry>
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

关于Azure API 管理 : Using OAuth to secure a connection between the gateway and a backend?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53780588/

相关文章:

azure - Azure 认知服务文本分析 API 中的事务是什么

android - 通过 ID token 从服务器检索 Google 用户数据

ruby-on-rails - 使用 OAuth 时 Heroku 上的 SSL 错误

Azure Function Timer 触发器和 API 管理 - 手动执行返回 404

azure - 无法在 Azure 中访问我的 X509Certificate2 的私钥

bash - 在 Azure Devops 中,如何在 "Azure CLI task v.2"运行的 shell 脚本中使用管道变量?

azure - Terraform 应用到 Azure - 在哪里可以看到通过对 Azure 运行应用所做的更改列表

oauth - 如何区分 JWT 访问 token 和用作授权 header 的刷新 token

azure - 有没有办法在 Azure 虚拟机上启用 CORS?

powershell - 使用 powershell 将带有模板参数的操作添加到 azure api