title: Logging API calls under AAD credentials
body: <p>I have a bunch of API's running in Azure behind an APIM which require OIDC authentication by my AAD and everything works as expected but I'm wondering what would be the best way to go about monitoring/logging which user calls which API. The information is available in the JWT generated by the OIDC service of the APIM so I would expect it to be possible.</p>
  
  <p>The default APIM service Analytics log some basic information for instance, without doing anything special, each call get's logged under user "Anonymous" with a randomly generated (persistent?) user id.</p>
  
  <p>I can create a bunch of APIM Users and hand out the corresponding subscription keys to my AAD Users and add the keys to their headers when making the request. With this the calls get logged under their names which is exactly what I would like. The problem with this is that it doesn't seem particularly safe. What prevents the sharing of the subscription keys and/or the mismatch between AAD User credentials an APIM subscription key?</p>
  
  <p>What would be the proper way to do this? Can it be done from within the APIM/AAD or do I need to use something like the Event Hubs?</p>
  
  <p>Edit:</p>
  
  <p>I found a solution that kinda works. By enabling Application Insights the following inbound API policy stores the name field of the JWT token as a trace. </p>
  
  <pre><code>&lt;trace source="MyApi" severity="information"&gt;
      &lt;message&gt;@(context.Request.Headers.GetValueOrDefault("Authorization","No auth header").AsJwt()?.Claims.GetValueOrDefault("name", "No name field"))&lt;/message&gt;
  &lt;/trace&gt;
  </code></pre>
  
  <p>Perhaps I should also add a policy if the JWT doesn't contain a field name and refuse the API call (bad request maybe).</p>
  
  <p>Anyway, this sounds like <em>a</em> way but not the proper solution that doesn't seem like that of an unique problem.</p>