title: Authenticate with Dynamics 365 from an Azure Function
body: <h2>Scenario</h2>
  
  <p>I have a Dynamics 365 v9 organisation hosted online. I have a set of Azure Functions hosted in an Azure Function App on a different tenant to my Dynamics organisation.</p>
  
  <p>I've created <a href="https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/use-webhooks" rel="nofollow noreferrer">web hooks</a> using the Dynamics Plugin Registration Tool, which at certain events (such as when a Contact is created in Dynamics), POST data to my Azure Functions via their endpoint URLs.</p>
  
  <p>Authentication between Dynamics 365 and my Azure Functions is achieved by passing an <code>x-functions-key</code> value in the HTTP request's authentication HttpHeader.</p>
  
  <p>The Azure Functions receive data from the event in Dynamics in the form of a <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.xrm.sdk.remoteexecutioncontext?view=dynamics-general-ce-9" rel="nofollow noreferrer">RemoteExecutionContext</a> which I can read using the following code:</p>
  
  <pre><code>using System.Net;
  
  public static async Task&lt;HttpResponseMessage&gt; Run(HttpRequestMessage req, TraceWriter log)
  {
      var jsonContent = await req.Content.ReadAsStringAsync();
  
      log.Info(jsonContent);
  
      return req.CreateResponse(HttpStatusCode.OK);
  }
  </code></pre>
  
  <h2>Question</h2>
  
  <p>How can the Azure Function then authenticate back with the calling Dynamics 365 organisation to read and write data?</p>
  
  <h2>What I've tried</h2>
  
  <ol>
  <li>Xrm Tooling</li>
  </ol>
  
  <p>The simplest way to authenticate would be to use the <a href="https://msdn.microsoft.com/en-gb/library/microsoft.xrm.tooling.connector.crmserviceclient.aspx" rel="nofollow noreferrer">CrmServiceClient</a> from Microsoft.Xrm.Tooling.Connector.dll. However, I don't necessarily have a username and password to provide the CrmServiceClient's constructor. Perhaps credentials could be passed securely via the HTTP POST request?</p>
  
  <ol start="2">
  <li>Application User</li>
  </ol>
  
  <p>I've tried registering an Application User in Dynamics. I supply the client id and client secret to my Azure Functions, but authentication fails because the user is in a different tenant to my Azure Functions.</p>
  
  <h2>Considered Solutions</h2>
  
  <p>One object of the received <code>jsonContent</code> string is called <code>ParentContext</code> . Perhaps this can be reused to authenticate back with the calling Dynamics organisation.</p>
  
  <p>Marc Schweigert has recommended using S2S and has provided a sample to his <a href="https://github.com/devkeydet/CrmAsyncRequestResponseSampleV2/blob/master/AzureFunctionApp/QueueListener.cs" rel="nofollow noreferrer">AzureFunctionApp</a> repository. If I can get this approach to work I'll post the solution here.</p>