1
votes

Following below document provided by Microsoft, I have registered both apps, setup OAuth 2.0 service with client-credentials and added "validate-jwt" inbound policy. I have tested it with postman generating bearer token and calling my backend API under APIM instance passing with token. It works fine.

https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-protect-backend-with-aad

But just along with Apim, I want to secure my backend API also and pass to same token to backend API. so I have some questions here -

  • Does APIM forward same bearer token to backend API automatically or do we need to configure any policy for it?
  • If it does, how can I check trace logs? Also how can I authorize that same token in backend API code?

Here is my "validate-jwt" policy -

<inbound>
    <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
        <openid-config url="https://login.microsoftonline.com/{AAD Tenant ID}/v2.0/.well-known/openid-configuration" />
        <audiences>
            <audience>{App Id of backend App}</audience>
        </audiences>
    </validate-jwt>
    <base />
</inbound>

Please help.

1

1 Answers

1
votes

For your first question:

According to some test in my side, it seems APIM can forward the same bearer token to backend api automatically, without adding any policy.

I created a api in APIM to call microsoft graph api(list users) in backend. Test to run the APIM api, it shows "401 Unauthorized" error. Then I test with provide the bearer token in headers of APIM api as below screenshot: enter image description here

It runs success and response the user list. So the bearer token can be forward to backend api automatically.

For your second question:

If you want to trace logs for the backend api, I think you can just do it in the backend code of your api.

To validate the token in your backend api, you can decode the jwt token in your backend api code and then check the value of claim in token(below I provide a sample to decode jwt token and get the value of iss claim)

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            var stream = "your access token";
            var handler = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadToken(stream);
            var tokenS = handler.ReadToken(stream) as JwtSecurityToken;

            var iss = tokenS.Claims.First(claim => claim.Type == "iss").Value;
            Console.WriteLine(iss);
            //Then check if "iss" matches the value you specified.

            Console.ReadLine();
        }
    }
}