0
votes

I currently have an API setup in Azure APIM with multiple operations. I have implemented a JWT Bearer authentication policy on the All Operations section.

What I need to do now is implement the authorization part per operation based on the scopes returned in my token. I've looked at this example and understand what to do API Authorization Restriction

However, is it good/bad practice to try implement the policy on the root All operations and then in that policy check the operation being requested and write the code to match the correct scopes to operation.

Or should the JWT policy be copy/pasted for each operation and only that operations authorization logic then lives in there.

Thanks in advance.

1

1 Answers

2
votes

So you're able to apply policies at the Global, Product , API and granular operation levels.

These policies are then evaluated together to form an Effective Policy for your request.

What I ended up doing was the applying the validate-jwt policy at the All Operations level. This means that for any operation in my API, my token would be authenticated.

<policies>
<inbound>
    <base />
    <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Not authenticated, token invalid." output-token-variable-name="jwt">
        <openid-config url="redacted" />
        <audiences>
            <audience>redacted</audience>
        </audiences>
        <issuers>
            <issuer>redacted</issuer>
        </issuers>
    </validate-jwt>
</inbound>
<backend>
    <base />
</backend>
<outbound>
    <base />
</outbound>
<on-error>
    <base />
</on-error>

I then added policies to the operations to perform the authorization by checking the scopes parameter in my JWT token, using the choose when policy. You need to make sure that you add this after the <base/> policy element.

<policies>
<inbound>
    <base />
    <choose>
        <when condition="@(!((Jwt)context.Variables["jwt"]).Claims.GetValueOrDefault("scope").Contains("read:user"))">
            <return-response>
                <set-status code="403" reason="Forbidden" />
            </return-response>
        </when>
    </choose>
</inbound>
<backend>
    <base />
</backend>
<outbound>
    <base />
</outbound>
<on-error>
    <base />
</on-error>