Adventures in Azure API Management: Pay Attention to Order in Policies

API Management

I was trying to secure an Azure API Management (APIM) APIs with OAuth 2.0 and Azure AD per Protect API backend in API Management using OAuth 2.0 and Azure AD – Azure API Management | Microsoft Docs.

My APIM managed API calls a back-end .NET Core API secured with Managed Identity.

In my policy, which I set for all operations, I get a Bearer token using the APIM policy authentication-managed-identity.

This policy will add the Authorization header for the Bearer token.

For more information on how to secure a .NET Core Web API in Azure see Adventures with Azure: Security, Azure App Services and Azure API Management | Matt Ruma.

Now, my front-end, or client app, authenticates to Azure AD and passes the Bearer token in the Authorization header to the APIM API call, which I want my policy to validate.

I do this with the APIM policy validate-jwt.

Everything was setup properly, but I kept getting a 401 Unauthorized error when I made the call to the APIM API from Postman.

After what seemed like hours – that may be a bit of an exaggeration, but it sure felt like it – I finally figured it out.

What was happening?!

When the policy executed, it would get the Bearer token from the authentication-managed-identity policy so it could call the back-end API, which in turn, would assign the Bearer token to the Authorization header, which effectively OVERWROTE the Bearer token I was passing in from my client app, this causing the validate-jwt to fail the authority validation.

In hind-sight, it makes perfect sense!

Easy fix! I switched the order of the authentication-managed-identity policy and validate-jwt and it started working.

Hope this helps someone! If not, I am sure it will help my future self, as I seem to forget more things than I remember.


Discover more from Matt Ruma

Subscribe to get the latest posts sent to your email.

2 Replies to “Adventures in Azure API Management: Pay Attention to Order in Policies”

  1. This is a life saver! We were facing the exact same issue and did not realise it’s such a simple fix. Thanks a lot Matt.

Leave a Reply

Your email address will not be published. Required fields are marked *