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