How to use Azure API Management Policies to log the calling client Azure AD application

My GitHub repo shows you how to build a simple web app that has a user interactively sign-in and then call an API protected via the OAuth2 validate-jwt token policy. There is also an example of a daemon (background process with no user interactively signed in) accessing this same API. The APIM policy will also log the Application ID of the calling AAD application and log the request to Azure Event Hub for further processing.

authorizationEventHubArchitecture

In both cases, the APIM & backing API don’t know or care about how the calling application authenticated & got an access token (either via Authorization Code Flow or Client Credential Flow). The same validate-jwt policy can be used for both.

How logging AAD client app works in APIM policy

The APIM XML policy below is based on the Advanced Monitoring documentation page. It also includes code to decode the JWT token that is received on every API call, decode it, capture the appid claim and then send it to Event Hub so we can capture the calling AAD application.

<log-to-eventhub logger-id="eventHubLogger" partition-id="0">@{
          var requestLine = string.Format("{0} {1} HTTP/1.1\r\n",
                                                      context.Request.Method,
                                                      context.Request.Url.Path + context.Request.Url.QueryString);

          var body = context.Request.Body?.As<string>(true);
          if (body != null && body.Length > 1024)
          {
              body = body.Substring(0, 1024);
          }

          var headers = context.Request.Headers
                               .Where(h => h.Key != "Authorization" && h.Key != "Ocp-Apim-Subscription-Key")
                               .Select(h => string.Format("{0}: {1}", h.Key, String.Join(", ", h.Value)))
                               .ToArray<string>();

          var headerString = (headers.Any()) ? string.Join("\r\n", headers) + "\r\n" : string.Empty;

            var jwt = context.Request.Headers.GetValueOrDefault("Authorization",string.Empty).Split(' ').Last().AsJwt();

            var appId = jwt.Claims.GetValueOrDefault("appid", string.Empty);

                      return "request:"   + context.Variables["message-id"] + "\n"
                              + requestLine + headerString + "\r\n" + body + "\n"
                              + "appId:" + appId;
      }</log-to-eventhub>

Pre-requisites

Run the sample apps

Set up Event Hub logging in VS Code to see appid captured from access tokens

  1. Open VS Code.
  2. Open the Command Palette (Ctrl+Shift+P) and type in EventHub: Select EventHub. Select your Event Hub.
  3. Open the Command Palette (Ctrl+Shift+P) and type in EventHub: Start Monitoring Event Hub Message.This will open the Azure Event Hub Explorer Output window.As you run each app, you will see the output from the Event Hub logger policy in APIM, capturing the appid field.

Run the user app

  1. Update the /web/client/user/appsettings.json file with your local values.
    • You can get a EchoAPISubscriptionKey from the Azure portal. Open the API Management instance and click on the subscriptions blade. Select a Product and click on the ellipsis, then click on Show/hide keys.
  2. Run the .NET codedotnet run –project ./web/client/user
  3. Run the Azure Event Hub Explorer to see the messages being sent to the eh-logicApimKey-ussc-demo topic.
  4. Open a browser to the default address (https://localhost:7071)
  5. Sign-in if prompted
  6. Click on the Call API button
  7. Notice the values that have been sent to the Event Hub from your policy in APIM.

Run the api app

  1. Update the /web/client/api/appsettings.json file with your local values.
    • You can get a EchoAPISubscriptionKey from the Azure portal. Open the API Management instance and click on the subscriptions blade. Select a Product and click on the ellipsis, then click on Show/hide keys.
  2. Run the .NET codedotnet run –project ./web/client/api
  3. Run the Azure Event Hub Explorer to see the messages being sent to the eh-logicApimKey-ussc-demo topic.
  4. Open a browser to the default address (https://localhost:7108)
  5. Sign-in if prompted
  6. Change the URL to the API endpoint (https://localhost:7108/vehicle)
  7. Notice the values that have been sent to the Event Hub from your policy in APIM.

Links

Related Posts

Leave a Reply

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