title: Query Azure SQL Database from local Azure Function using Managed Identities
body: <p>I want to query an Azure SQL Database from an Azure Function executing on my machine in debug using Managed Identities (i.e. the identity of my user connected to Visual Studio instead of providing UserId and Password in my connection string).</p>
  
  <p>I followed <a href="https://docs.microsoft.com/fr-fr/azure/app-service/app-service-web-tutorial-connect-msi" rel="nofollow noreferrer">this tutorial</a> on Microsoft documentation so my Azure SQL Server has an AD user as admin which allowed me to give rights (db_datareader) to an Azure AD group I created with my Azure Function Identity and my user in it (and also my Function App deployed in Azure).</p>
  
  <p>If I deploy and run in Azure my Azure Function, it is able to query my database and everything is working fine. But when I run my Azure Function locally, I have the following error : </p>
  
  <blockquote>
    <p>Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.</p>
  </blockquote>
  
  <p>The code of my function is the following:</p>
  
  <pre class="lang-cs prettyprint-override"><code>    public async Task&lt;IActionResult&gt; Run(
          [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "test")] HttpRequest req,
          ILogger log)
      {
          log.LogInformation("C# HTTP trigger function processed a request.");
  
  
          using (var connection = new SqlConnection(Environment.GetEnvironmentVariable("sqlConnectionString")))
          {
              connection.AccessToken = await (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net");
              log.LogInformation($"Access token : {connection.AccessToken}");
              try
              {
                  await connection.OpenAsync();
                  var rows = await connection.QueryAsync&lt;Test&gt;("select top 10 * from TestTable");
                  return new OkObjectResult(rows);
              }
              catch (Exception e)
              {
                  throw e;
              }
  
          }
      }
  </code></pre>
  
  <p>The code retrieves a token correctly, the error occurs on line <code>await connection.OpenAsync()</code>. </p>
  
  <p>If I open the database in Azure Data Studio with the same user than the one connected to Visual Studio (which is member of the AD group with the rights on the database), I can connect and query the database without any issue.</p>
  
  <p>Is it a known issue or am I missing something here ?</p>