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

本小妞迷上赌 提交于 2021-02-20 03:49:16

问题


I have the same API running multiple times connecting to different databases which represents the private data of each user that connects.

I have one web site that authenticates with Active Directory to determine which user is connected. The same API calls are made whichever user is logged in, however, the host at the root of the API call needs to be dependent on the user logged in.

How do I configure Azure API Management to route to the correct host depending on which user is logged in?

A simple policy that routes to 2 different function apps based on true/false is:

 <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>

How do I modify this to make the choice based on the user that is logged in to the web app?


回答1:


Use set backend policy to change backend on the fly




回答2:


Azure API Management has Users and Groups built in to it (although it is possible to use external sources like AD as well).

If you use these Users and Groups (and not the external ones) you can write a policy like this to do the routing:

<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>


来源:https://stackoverflow.com/questions/56909632/how-do-i-configure-azure-apim-to-route-to-different-backends-based-on-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!