title: Azure Function authentication using Azure Active Directory
body: <p>I wanted to enable authentication on Azure Functions. So, I decided to go with EasyAuth (Authentication/Authorization link under platform features) and was successfully able to configure the authentication process.</p>
  <p>The authentication works when I manually sign-in to the Azure Function endpoint. But when I try to programmatically access the API, without any manual user intervention, I'm facing authentication issue:</p>
  <pre><code>Status Code:401, Unauthorized
  </code></pre>
  <p>I get an access token from AAD using clientID and clientSecret using the following code:</p>
  <pre><code>AuthenticationContext context = new AuthenticationContext(&quot;https://login.windows.net/&lt;tenant-id&gt;&quot;);
  string key = &quot;&lt;client-secret&gt;&quot;;
  ClientCredential cc = new ClientCredential(&quot;&lt;client-id&gt;&quot;, key);
  AuthenticationResult result = context.AcquireTokenAsync(&quot;https://&lt;AzureFunctionAppName&gt;.azurewebsites.net/&quot;, cc).Result;
  return result.AccessToken;
  </code></pre>
  <p>Then I'm trying to send the Access Token received in the header for a new request to my API:</p>
  <pre><code>var content = &quot;{\&quot;on\&quot;:true, \&quot;sat\&quot;:254, \&quot;bri\&quot;:254, \&quot;hue\&quot;:10000}&quot;;
  var AADToken = GetS2SAccessToken();
  HttpClient Client = new HttpClient();
  Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, AADToken);
  var foo = Client.PostAsync(&quot;https://&lt;AzureFunctionAppName&gt;.azurewebsites.net/.auth/login/aad&quot;, new StringContent(content.ToString())).Result;
  Console.WriteLine($&quot;result: {foo}&quot;);
  </code></pre>
  <p>But the above code is resulting in unauthorized calls. I am not sure what I'm doing wrong.</p>