0
votes

I have two scenarios where in first client will call the APIM with bearer token and other one is Function App will call our APIM with Managed identity. I have the code which will validate the jwt. but I want to know how can I skip the other one if either one is available(e.g I want to skip the jwt validation if its get called with managed Identity). From examples I can see I can do a choose and when but not sure what will be the headers for the managed identity. Here is what I am thinking I should be updating.

<choose>
    <when condition="@(context.Request.Headers.GetValueOrDefault("Authorization","") != "")">
         <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Invalid or Expired token" require-expiration-time="true" require-signed-tokens="true">
            <openid-config url=".well-known/openid-configuration" />
            <audiences>
                <audience>audience</audience>
            </audiences>
            <issuers>
                <issuer>issuer</issuer>
            </issuers>
        </validate-jwt>
    </when>
<when condition="to validate managed identity">
<authentication-managed-identity resource="resource" client-id="clientid of user-assigned identity" output-token-variable-name="token-variable" ignore-error="true|false"/>
</when>
</choose>
1
<authentication-managed-identity> is used to authenticate apim to the resource that you are going to call. Not the other way around.SteppingRazor

1 Answers

0
votes

For this requirement, I think there isn't any difference between the two request(request APIM with bearer token directly and request APIM from function app by managed identity). Both of them will provide a bearer token in header(Authorization) of the request.

You can refer to this document about calling APIM from function app according to managed identity. You can find the lines of code shown as below in the document which are used to get access token and set the token in header when request APIM.

var azureServiceTokenProvider = new AzureServiceTokenProvider(identity);
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(target,tenantID);

wc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

So the second request scenario is same with the first request scenario. We can not distinguish them in APIM policy before <validate-jwt>. To implement your requirement, I think you can add a property into the header of the two requests and then check the header in APIM policy. For example, in function app code, you can add a header like below:

httpClient.DefaultRequestHeaders.Add("comeFrom", "fromFunApp");

Then check the header in policy:

<choose>
    <when condition="@(context.Request.Headers.GetValueOrDefault("comeFrom","") != "fromFunApp" && context.Request.Headers.GetValueOrDefault("Authorization","") != "")">
    ..............