title: Connect Azure CosmosDB using Managed Identities from Azure Function App both locally and on Azure
body: <p>I create a Managed Identity for a Function app and assigned it to <code>DocumentDB Account Contributor</code> by following the two sections below</p>
  <p><a href="https://docs.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#assign-a-system-assigned-managed-identity-to-a-function-app" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#assign-a-system-assigned-managed-identity-to-a-function-app</a></p>
  <p><a href="https://docs.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#grant-access-to-your-azure-cosmos-account" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#grant-access-to-your-azure-cosmos-account</a></p>
  <p><strong>Microsoft.Azure.Services.AppAuthentication</strong></p>
  <p>I got an exception when I tried to run the code from the section below:</p>
  <p><a href="https://docs.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#programmatically-access-the-azure-cosmos-db-keys" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#programmatically-access-the-azure-cosmos-db-keys</a></p>
  <blockquote>
  <p>Could not load file or assembly 'System.Text.Encodings.Web,
  Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
  The system cannot find the file specified.
  at
  System.Text.Json.Serialization.Metadata.JsonPropertyInfo.DeterminePropertyName()
  at
  System.Text.Json.Serialization.Metadata.JsonPropertyInfo.GetPolicies(Nullable<code>1 ignoreCondition, Nullable</code>1 declaringTypeNumberHandling)    at
  ...
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
  at
  Cosmos.Samples.AzureFunctions.AzureFunctionsCosmosClientMI.d__7.MoveNext()
  in
  C:.ME\MyLab.Code\AzureCode\CosmosDB\azure-cosmos-dotnet-v3-usage\AzureFunctions\AzureFunctionsCosmosClientMI.cs:line
  85</p>
  </blockquote>
  <p><strong>Azure.Identity</strong></p>
  <p>Since <code>AppAuthentication</code> is not recommended by MS, then I switched to using <code>Azure.Identity</code> by following the links below:
  <a href="https://docs.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet</a></p>
  <p><a href="https://joonasaijala.com/2021/07/01/how-to-using-managed-identities-to-access-cosmos-db-data-via-rbac-and-disabling-authentication-via-keys/" rel="nofollow noreferrer">https://joonasaijala.com/2021/07/01/how-to-using-managed-identities-to-access-cosmos-db-data-via-rbac-and-disabling-authentication-via-keys/</a></p>
  <p>and the code below</p>
  <pre><code> static string cosmosUrl = &quot;https://xxx.documents.azure.com:443/&quot;;
      private static CosmosClient client = new CosmosClient(cosmosUrl, new DefaultAzureCredential());
     var container = client.GetContainer(&quot;FamilyDatabase&quot;, &quot;FamilyContainer&quot;);
          try
          {
              var result = await container.CreateItemAsync&lt;Item&gt;(data, new PartitionKey(data.LastName));
              return new OkObjectResult(result.Resource.Id);
          }
          catch (CosmosException cosmosException)
          {
              log.LogError(&quot;Creating item failed with error {0}&quot;, cosmosException.ToString());
              return new BadRequestObjectResult($&quot;Failed to create item. Cosmos Status Code {cosmosException.StatusCode}, Sub Status Code {cosmosException.SubStatusCode}: {cosmosException.Message}.&quot;);
          }
  </code></pre>
  <p>However, I got the exception below both locally and running it in Azure.</p>
  <blockquote>
  <p>Failed to create item. Cosmos Status Code Forbidden, Sub Status Code
  5301: Response status code does not indicate success: Forbidden (403);
  Substatus: 5301; ActivityId: xxxx-bf03-4355-8642-5d316f9d3373;
  Reason: (Request blocked by Auth xxxx : Request is blocked because
  principal [xxx-2bff-44e9-97be-9ffeb3aae3ee] does not have
  required RBAC permissions to perform action
  [Microsoft.DocumentDB/databaseAccounts/readMetadata] on resource [/].
  Learn more: <a href="https://aka.ms/cosmos-native-rbac" rel="nofollow noreferrer">https://aka.ms/cosmos-native-rbac</a>. ActivityId:
  xxx-bf03-4355-8642-5d316f9d3373,
  Microsoft.Azure.Documents.Common/2.14.0, Windows/10.0.14393
  cosmos-netstandard-sdk/3.24.1);.</p>
  </blockquote>
  <p>Locally, I logged into VS following the link
  <a href="https://docs.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#authenticating-via-visual-studio" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#authenticating-via-visual-studio</a></p>
  <p>Any idea for resolving issues with Azure.Identity?</p>
  <p>Ref:</p>
  <p><a href="https://stackoverflow.com/questions/67512766/connect-function-app-to-cosmosdb-with-managed-identity">Connect Function App to CosmosDB with Managed Identity</a></p>
  <p><a href="https://github.com/Azure/azure-sdk-for-net/tree/Azure.Identity_1.5.0/sdk/identity/Azure.Identity/samples" rel="nofollow noreferrer">https://github.com/Azure/azure-sdk-for-net/tree/Azure.Identity_1.5.0/sdk/identity/Azure.Identity/samples</a></p>