如何配置 Azure APIM 以根据用户路由到不同的后端?

How Do I Configure Azure APIM To Route To Different Backends Based On The User?

我有相同的 API 运行 多次连接到不同的数据库,这代表了每个连接用户的私有数据。

我有一个网站使用 Active Directory 进行身份验证以确定哪个用户已连接。无论哪个用户登录,都会进行相同的 API 调用,但是,API 调用的根目录主机需要依赖于登录的用户。

如何配置 Azure API 管理以根据登录的用户路由到正确的主机?

基于true/false 路由到 2 个不同功能应用程序的简单策略是:

 <policies>
    <inbound>
        <base />
        <set-method>GET</set-method>
        <choose>
            <when condition="true">
                <set-backend-service base-url="https://abc-apim.azure-api.net/org2app" />
            </when>
            <when condition="false">
                <set-backend-service base-url="https://abc-apim.azure-api.net/org1app" />
            </when>
        </choose>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

我如何修改它以根据登录到网络应用程序的用户做出选择?

使用设置后端策略即时更改后端

Azure API 管理内置了用户和组(尽管也可以使用 AD 等外部资源)。

如果您使用这些用户和组(并且不是外部用户和组),您可以编写这样的策略来执行路由:

<policies>
    <inbound>
        <choose>
            <when condition="@(context.User.Groups.Select(g => g.Name).Contains("org1"))">
                <set-backend-service base-url="https://abc-apim.azure-api.net/org1app" />
            </when>
            <when condition="@(context.User.Groups.Select(g => g.Name).Contains("org2"))">
                <set-backend-service base-url="https://abc-apim.azure-api.net/org2app" />
            </when>
            <otherwise>
                <return-response>
                    <set-status code="401" reason="Unauthorized" />
                    <set-header name="WWW-Authenticate" exists-action="override">
                        <value>Bearer error="Invalid user group"</value>
                    </set-header>
                </return-response>
            </otherwise>
        </choose>
        <base />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>